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