码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-12-09 16:19:44      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:nbsp   运行   处理   cli   const   按钮   箭头函数   his   方式   

绑定函数事件

在以类继承的方式定义的组件中,为了能方便地调用当前组件的其他成员方法或属性(如: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> 

 

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

标签:nbsp   运行   处理   cli   const   按钮   箭头函数   his   方式   

原文地址:https://www.cnblogs.com/juewuzhe/p/10090783.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!