You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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>);}}
属性初始化器语法
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>);}}
回调函数中使用 箭头函数
classLoggingButtonextendsReact.Component{handleClick(){console.log('this is:',this);}render(){// This syntax ensures `this` is bound within handleClickreturn(<buttononClick={(e)=>this.handleClick(e)}>
Click me
</button>);}}
#this #React #bind
类(React.Component 构造的组件)的方法默认是不会绑定 this 的。
一共有三种方法解决
注意点
传递参数
参数 e 作为 React 事件对象将会被作为第二个参数进行传递。通过箭头函数的方式,事件对象必须显式的进行传递,但是通过 bind 的方式,事件对象以及更多的参数将会被隐式的进行传递。
The text was updated successfully, but these errors were encountered: