class App extends React.Component {
state = {
counter: 0,
};
handleClick=()=> {
const counter = this.state.counter;
this.setState({counter: counter + 1});
};
//如果写成下面的形式,则点击无效,这两者区别是什么
handleClick(){
const counter = this.state.counter;
this.setState({counter: counter + 1});
};
render() {
return (
<div>
counter is: {this.state.counter}
<button onClick={this.handleClick}>点我</button>
</div>
)
}
}
这个涉及到
js
的一些特性当你在
react
的jsx
中this.handleClick
的时候 实际就是obj.show
把这个函数传过去了,this
就是在这个时候丢失的这是
jsx
编译成js
之后,我们只能获取到onClick
就是temp
箭头函数 或者
bind
都是为了在调用之前 就把this
给绑定