react 向事件处理程序传递参数

通常我们会为事件处理程序传递额外的参数。例如,若是 id 是一个内联 id,以下两种方式都可以向事件处理程序传递参数:



上述两种方式是等价的,分别通过 arrow functions 和 Function.prototype.bind 来为特定事件类型添加事件处理程序。

上面两个例子中,参数 e 作为 React 事件对象将会被作为第二个参数进行传递。通过箭头函数的方式,事件对象必须显式的进行传递,但是通过 bind 的方式,事件对象以及更多的参数将会被隐式的进行传递。

值得注意的是,通过 bind 方式向监听函数传参,在类组件中定义的监听函数,事件对象 e 要排在所传递参数的后面,例如:

class Popper extends React.Component{
    constructor(){
        super();
        this.state = {name:'Hello world!'};
    }
    
    preventPop(name, e){    //事件对象e要放在最后
        e.preventDefault();
        alert(name);
    }
    
    render(){
        return (
            

hello

{/* Pass params via bind() method. */} Click
); } }

你可能感兴趣的:(react 向事件处理程序传递参数)