react合成事件的三种绑定方式bind
2017-07-25 08:57
447 查看
在使用ES6 classes或者纯函数时,不存在自动绑定,需要我们手动实现this的绑定。
一 bind方法。这个方法可以绑定事件处理器内的this,并可以向事件处理器中传递参数,例:
二 构造器内声明,优点为仅需要进行一次绑定,不需要每次调用时去执行绑定。
class App extends Component{
constructor(props){
super(props);
this.handleClick=this.handleClick.bind(this)
}
handleClick(){
console.log("ok")
}
render(){
return(
<button onClick={this.handleClick}>按钮</button>
)
}
}
三 箭头函数,自动绑定了定义此函数作用域的this。
一 bind方法。这个方法可以绑定事件处理器内的this,并可以向事件处理器中传递参数,例:
class App extends Component{ handleClick(e,arg){ console.log(e,arg); } render(){ return<button onClick={this.handleClick.bind(this,'test')}>Test</button>; } }若不传参即可写为
this.handleClick.bind(this)另外stage 0草案中提供了一个便捷的方案——双冒号语法,例:
<button onClick={::this.handleClick}>Test</button>
二 构造器内声明,优点为仅需要进行一次绑定,不需要每次调用时去执行绑定。
class App extends Component{
constructor(props){
super(props);
this.handleClick=this.handleClick.bind(this)
}
handleClick(){
console.log("ok")
}
render(){
return(
<button onClick={this.handleClick}>按钮</button>
)
}
}
三 箭头函数,自动绑定了定义此函数作用域的this。
class App extends Component{ const handleClick=(e)=>{ console.log(e); } render(){ return<button onClick={this.handleClick}>Test</button>; } }或
class App extends Component{ handleClick(e){ console.log(e); } render(){ return<button onClick={()=>this.handleClick()}>Test</button>; } }
相关文章推荐
- jQuery三种事件绑定方式.bind(),.live(),.delegate()
- jQuery三种事件绑定方式.bind(),.live(),.delegate()
- react绑定事件的三种方式
- jQuery三种事件绑定方式.bind(),.live(),.delegate()
- 【转载】jQuery三种事件绑定方式.bind(),.live(),.delegate()
- jQuery三种事件绑定方式.bind(),.live(),.delegate()原理对比
- jQuery三种事件绑定方式.bind(),.live(),.delegate()
- jquery 事件委托三种事件绑定方式.bind(),.live(),.delegate()
- jQuery三种事件绑定方式:bind(),.live(),.delegate()
- 浅谈Jquery中的bind(),live(),delegate(),on()绑定事件方式
- Dom事件的三种绑定方式
- Jquery中的bind(),live(),delegate(),on()绑定事件方式
- jQuery四种事件绑定方式.bind(),.live(),.delegate(),on()的区别
- jQuery绑定事件的四种方式:bind、live、delegate、on
- 【jquery】jquery绑定事件的方式 bind() delegate() live()以及on()
- Jquery中的bind(),live(),delegate(),on()绑定事件方式的区别
- Jquery 的bind(), live(), delegate(), on()绑定事件方式
- Jquery中的bind(),live(),delegate(),on()绑定事件方式
- 浅谈Jquery中的bind(),live(),delegate(),on()绑定事件方式
- 【jquery】jquery绑定事件的方式 bind() delegate() live()以及on()