react事件和原生HTML的区别:
function ActionLink() { function handleClick(e) { e.preventDefault(); console.log(‘The link was clicked.‘); } return ( <a href="#" onClick={handleClick}> Click me </a> ); }
class Toggle extends React.Component { constructor(props) { super(props); this.state = {isToggleOn: true}; // 为了在回调中使用 `this`,这个绑定是必不可少的 this.handleClick = this.handleClick.bind(this); } handleClick() { this.setState(state => ({ isToggleOn: !state.isToggleOn })); } render() { return ( <button onClick={this.handleClick}> {this.state.isToggleOn ? ‘ON‘ : ‘OFF‘} </button> ); } } ReactDOM.render( <Toggle />, document.getElementById(‘root‘) );
class Toggle extends React.Component { constructor(props) { super(props); this.state = {isToggleOn: true}; } //class fields语法 handleClick = () => { this.setState(state => ({ isToggleOn: !state.isToggleOn })); } render() { return ( <button onClick={this.handleClick}> {this.state.isToggleOn ? ‘ON‘ : ‘OFF‘} </button> ); } } ReactDOM.render( <Toggle />, document.getElementById(‘root‘) );
class Toggle extends React.Component { constructor(props) { super(props); this.state = {isToggleOn: true}; } handleClick() { this.setState(state => ({ isToggleOn: !state.isToggleOn })); } render() { return ( <button onClick={(e) => this.handleClick(e)}> {this.state.isToggleOn ? ‘ON‘ : ‘OFF‘} </button> ); } } ReactDOM.render( <Toggle />, document.getElementById(‘root‘) );
注意:语法3中回调函数作为props传入子组件时,这些组件可能会额外重新渲染,所以我们建议使用1、2语法来避免出现性能问题
<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button> <button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>
原文:https://www.cnblogs.com/gopark/p/12292164.html