React事件绑定相似于DOM事件绑定,区别以下:函数
以下实例:this
<a href="#" onclick="console.log('The link was clicked.'); return false"> Click me </a> class ActionLink extends React.Component { constructor(props) { super(props); } handleClick(e) { e.preventDefault(); console.log('The link was clicked.'); } render() { return ( <a href="#" onClick={this.handleClick.bind(this)}>Click Me...</a> ); } }
ps:React组件类的方法没有默认绑定this到组件实例,须要手动绑定。code
在调用方法的地方直接经过调用bind方法来绑定,也能够在构造函数里面直接用bind方法绑定this.事件
class Toggle extends React.Component { constructor(props) { super(props); this.state = { isToggleOn: true }; //this.toggleHander = this.toggleHander.bind(this); } toggleHander() { this.setState(preState => ({ isToggleOn: !preState.isToggleOn })); } render() { return ( <button onClick = { this.toggleHander.bind(this) }>{this.state.isToggleOn ? 'ON' : 'OFF'}</button> ); } }
类的属性初始化语法(该用法还未写入es标准,有兼容问题)jsx
class Toggle extends React.Component { constructor(props) { super(props); this.state = { isToggleOn: true }; } toggleHander = () => { this.setState(preState => ({ isToggleOn: !preState.isToggleOn })); } render() { return ( <button onClick = { this.toggleHander}>{this.state.isToggleOn ? 'ON' : 'OFF'}</button> ); } }
箭头函数字符串
class Toggle extends React.Component { constructor(props) { super(props); this.state = { isToggleOn: true }; //this.toggleHander = this.toggleHander.bind(this); } toggleHander() { this.setState(preState => ({ isToggleOn: !preState.isToggleOn })); } render() { return ( <button onClick = { (e) => this.toggleHander(e) }>{this.state.isToggleOn ? 'ON' : 'OFF'}</button> ); } }
ps:推荐在构造函数中绑定相关方法的this指向,或者将方法写成类字段的形式。避免某些方法做为属性向子组件传递引发的一些问题。io