React passing parameter via onclick event using ES6 syntax

前端 未结 8 891
死守一世寂寞
死守一世寂寞 2020-12-04 06:34

How to pass extra parameters to an onClick event using the ES6 syntax?

For instance:

handleRemove = (e) => {

}

render() {
     
8条回答
  •  醉酒成梦
    2020-12-04 06:58

    TL;DR:

    Don't bind function (nor use arrow functions) inside render method. See official recommendations.

    https://reactjs.org/docs/faq-functions.html


    So, there's an accepted answer and a couple more that points the same. And also there are some comments preventing people from using bind within the render method, and also avoiding arrow functions there for the same reason (those functions will be created once again and again on each render). But there's no example, so I'm writing one.

    Basically, you have to bind your functions in the constructor.

    class Actions extends Component {
    
        static propTypes = {
            entity_id: PropTypes.number,
            contact_id: PropTypes.number,
            onReplace: PropTypes.func.isRequired,
            onTransfer: PropTypes.func.isRequired
        }
    
        constructor() {
            super();
            this.onReplace = this.onReplace.bind(this);
            this.onTransfer = this.onTransfer.bind(this);
        }
    
        onReplace() {
            this.props.onReplace(this.props.entity_id, this.props.contact_id);
        }
    
        onTransfer() {
            this.props.onTransfer(this.props.entity_id, this.props.contact_id);
        }
    
        render() {
            return (
                
    ) } } export default Actions

    Key lines are:

    constructor

    this.onReplace = this.onReplace.bind(this);

    method

    onReplace() {
        this.props.onReplace(this.props.entity_id, this.props.contact_id);
    }
    

    render

    onClick={this.onReplace}
    

提交回复
热议问题