React(5) --绑定函数事件

绑定函数事件

在以类继承的方式定义的组件中,为了能方便地调用当前组件的其他成员方法或属性(如:this.state),通常需要将事件处理函数运行时的 this 指向当前组件实例。

run(){
    alert('我是一个run方法')
}

<button onClick={this.run}>执行方法</button> 

//方法不需要加(),加了(),一旦页面加载进来就执行了 

绑定事件处理函数this的几种方法:

方法1:

run(){
     alert(this.state.name)
}
<button onClick={this.run.bind(this)}>按钮</button>  //不绑定this的话,上面的方法里面的this就指向不了,拿不到数据

方法2:

constructor(props){
        super(props);   //固定写法

        this.state={

            name:'我是一个home组件'
           
        }   

        //构造函数中改变

        this.run = this.run.bind(this);

  }

run(){

        alert(this.state.name)
}
<button onClick={this.run}>按钮</button>

方法3:

//直接使用箭头函数 
run=()=> { alert(this.state.name) } <button onClick={this.run}>按钮</button>

函数方法里传值,改变state的值

setName=(str)=>{

      //改变state的值

      this.setState({

          username:str
      })

}
<button onClick={this.setName.bind(this,'张三')}>执行方法传值</button>

<button onClick={this.setName.bind(this,'张三','李四')}>执行方法传值</button> 

猜你喜欢

转载自www.cnblogs.com/juewuzhe/p/10090783.html