反应:“this”在组件函数中是未定义的

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对象在处理程序中是未定义的。 根据教程文档,我应该参考该组件。 我错过了什么吗?

ES6 React.Component不会自动将方法绑定到自己。 你需要在构造函数中自己绑定它们。 喜欢这个:

 constructor (props){ super(props); this.state = { loopActive: false, shuffleActive: false, }; this.onToggleLoop = this.onToggLoop.bind(this); } 

有几种方法。

一个是添加this.onToggleLoop = this.onToggleLoop.bind(this); 在构造函数中。

另一个是箭头函数onToggleLoop = (event) => {...}

然后是onClick={this.onToggleLoop.bind(this)}

我在渲染函数中遇到了类似的绑定,最终以如下方式传递了这个上下文:

 {someList.map(function(listItem) { // your code }, this)} 

我也用过:

 {someList.map((listItem, index) => <div onClick={this.someFunction.bind(this, listItem)} /> )} 

如果你在像componentDidMount这样的生命周期方法中调用你创build的方法 ,那么你只能使用this.onToggleLoop = this.onToogleLoop.bind(this)和胖箭头函数onToggleLoop = (event) => {...}

在构造函数中声明一个函数的正常方法不会起作用,因为生命周期方法在前面被调用。