gpt4 book ai didi

javascript - react : "this" is undefined inside a component function

转载 作者:行者123 更新时间:2023-11-28 03:43:41 25 4
gpt4 key购买 nike

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 应该引用该组件。我错过了什么吗?

最佳答案

ES6 React.Component 不会自动将方法绑定(bind)到自身。您需要自己在构造函数中绑定(bind)它们。像这样:

constructor (props){
super(props);

this.state = {
loopActive: false,
shuffleActive: false,
};

this.onToggleLoop = this.onToggleLoop.bind(this);

}

关于javascript - react : "this" is undefined inside a component function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48692514/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com