这是我的代码:
import React from 'react';
export default class MovieCard extends React.Component {
constructor(props) {
super(props);
this.state = { content: 'test' };
}
changer = () => {
this.setState({ content: 'changed' });
};
// changer() {
// this.setState({ content: 'changed' });
// }
render() {
return (
<div>
<h1>{this.state.content}</h1>
<button onClick={this.changer}>click me to change</button>
</div>
);
}
}
常规函数(我把它注释掉了)应该做同样的事情但它不起作用,而箭头函数起作用并改变 h1 元素的状态。
这是为什么呢?有什么问题吗?
最佳答案
如果您要使用它们,您需要绑定(bind)this
。箭头函数不需要绑定(bind),因为箭头函数在其上下文中没有以下内容:
这个
争论
super 好
新目标
constructor(props) {
super(props);
this.state = { content: "test" };
this.changer = this.changer.bind(this);
}
changer() {
this.setState({ content: "changed" });
}
render() {
return (
<div>
<h1>{this.state.content}</h1>
<button onClick={this.changer}>click me to change</button>
</div>
);
}
https://stackoverflow.com/questions/70641175/