【发布时间】:2018-12-18 03:14:54
【问题描述】:
有人可以向我解释为什么我在使用事件时需要使用绑定this.handleClick = this.handleClick.bind(this); 吗?
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
// This binding is necessary to make `this` work in the callback
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')
);
为什么要定义'this'的值?
class Person {
constructor(name, yearOfBirth) {
this.name = name;
this.yearOfBirth = yearOfBirth;
}
calculateAge() {
console.log(this);
}
}
const john = new Person('John', 1993);
john.calculateAge();
但是点击时'this'的值是不确定的?
function ActionLink() {
function handleClick(e) {
e.preventDefault();
console.log('The link was clicked.');
console.log(this);
}
return (
<a href="#" onClick={handleClick}>
Click me
</a>
);
}
ReactDOM.render(
<ActionLink />,
document.getElementById('root')
);
【问题讨论】:
-
你应该把这个问题分成两个问题。
-
将handleClick() 函数更改为this.handleClick() 并使用this.handleClick() 调用。你认为“这个”是什么?
-
所以在 react 组件中你可以使用
handleClick = () => {来声明this方法以避免使用bind。
标签: javascript reactjs