React:“this”在组件函数内部未定义
2015-11-28
174646
class PlayerControls extends React.Component {
constructor(props) {
super(props)
this.state = {
loopActive: false,
shuffleActive: false,
}
}
render() {
var shuffleClassName = this.state.toggleActive ? "player-control-icon active" : "player-control-icon"
return (
<div className="player-controls">
<FontAwesome
className="player-control-icon"
name='refresh'
onClick={this.onToggleLoop}
spin={this.state.loopActive}
/>
<FontAwesome
className={shuffleClassName}
name='random'
onClick={this.onToggleShuffle}
/>
</div>
);
}
onToggleLoop(event) {
// "this is undefined??" <--- here
this.setState({loopActive: !this.state.loopActive})
this.props.onToggleLoop()
}
我想在切换时更新
loopActive
状态,但
this
对象在处理程序中未定义。根据教程文档,我
this
应该引用组件。我遗漏了什么吗?
3个回答
ES6
React.Component
不会自动将方法绑定到自身。您需要在
constructor
中自行绑定它们。如下所示:
constructor (props){
super(props);
this.state = {
loopActive: false,
shuffleActive: false,
};
this.onToggleLoop = this.onToggleLoop.bind(this);
}
Ivan
2015-11-28
有几种方法。
一种是在构造函数中添加
this.onToggleLoop = this.onToggleLoop.bind(this);
。
另一种是箭头函数
onToggleLoop = (event) => {...}。
然后是
onClick={this.onToggleLoop.bind(this)}。
J. Mark Stevens
2015-11-28
按如下方式编写你的函数:
onToggleLoop = (event) => {
this.setState({loopActive: !this.state.loopActive})
this.props.onToggleLoop()
}
the binding for the keyword this is the same outside and inside the fat arrow function. This is different than functions declared with function, which can bind this to another object upon invocation. Maintaining the this binding is very convenient for operations like mapping: this.items.map(x => this.doSomethingWith(x)).
ShaTin
2017-12-04