React 事件传参和this绑定

    技术2023-11-18  88

    在类组件中定义的监听函数,事件对象 e 要排在所传递参数的后面,例如:

    class Popper extends React.Component{ constructor(){ super(); this.state = {name:'Hello world!'}; } preventPop(name, e){ //事件对象e要放在最后 e.preventDefault(); alert(name); } render(){ return ( <div> <p>hello</p> {/* 通过 bind() 方法传递参数。 */} <a href="https://reactjs.org" onClick={this.preventPop.bind(this,this.state.name)}>Click</a> </div> ); } }

    需要通过 bind 方法来绑定参数,第一个参数指向 this,第二个参数开始才是事件函数接收到的参数:

    <button onClick={this.handleClick.bind(this, props0, props1, ...}></button> handleClick(porps0, props1, ..., event) { // your code here }

    事件:this.handleclick.bind(this,要传的参数)

    函数:handleclick(传过来的参数,event)

    Processed: 0.013, SQL: 9