<!-- HTML -->
<a href="#" onclick="console.log('The link was clicked.'); return false">
Click me
</a>
becomes
//ReactfunctionActionLink() {functionhandleClick(e) {e.preventDefault();console.log('The link was clicked.'); }return ( <ahref="#"onClick={handleClick}> Click me </a> );}
e is a synthetic event handling cross-browser compat
Usage
Pass functions into event handlers
use event.persist(); if you access async because react event objects are recycled so could be different
classToggleextendsReact.Component {constructor(props) {super(props);this.state = {isToggleOn:true};// This binding is necessary to make `this` work in the callbackthis.handleClick =this.handleClick.bind(this); }handleClick() {this.setState(prevState => ({ isToggleOn:!prevState.isToggleOn })); }render() {return ( <buttononClick={this.handleClick}> {this.state.isToggleOn ?'ON':'OFF'} </button> ); }}ReactDOM.render( <Toggle />,document.getElementById('root'));
Bind()
[method].bind(this) is a vanilla JS function that sets the this ptr of the function to the arg passed needed when passing ft like in callbacks rather than calling it
Generally, if you refer to a method without () after it, such as onClick={this.handleClick}, you should bind that method.
Not using bind()?
classLoggingButtonextendsReact.Component {// This syntax ensures `this` is bound within handleClick.// Warning: this is *experimental* syntax.handleClick= () => {console.log('this is:',this); }render() {return ( <buttononClick={this.handleClick}> Click me </button> ); }}