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()
}
Run Code Online (Sandbox Code Playgroud)
我想loopActive在切换时更新状态,但是this在处理程序中未定义对象.根据教程文档,我this应该参考该组件.我错过了什么吗?
Iva*_*van 181
ES6 React.Component不会自动将方法绑定到自身.您需要在构造函数中自己绑定它们.像这样:
constructor (props){
super(props);
this.state = {
loopActive: false,
shuffleActive: false,
};
this.onToggleLoop = this.onToggleLoop.bind(this);
}
Run Code Online (Sandbox Code Playgroud)
J. *_*ens 79
有几种方法.
一种是this.onToggleLoop = this.onToggleLoop.bind(this);在构造函数中添加
.
另一个是箭头功能
onToggleLoop = (event) => {...}.
然后有onClick={this.onToggleLoop.bind(this)}.
小智 19
用这种方式写你的函数:
onToggleLoop = (event) => {
this.setState({loopActive: !this.state.loopActive})
this.props.onToggleLoop()
}
Run Code Online (Sandbox Code Playgroud)
http://www.react.express/fat_arrow_functions
关键字的绑定在胖箭头函数的外部和内部是相同的.这与使用function声明的函数不同,函数可以在调用时将其绑定到另一个对象.维护此绑定对于映射操作非常方便:this.items.map(x => this.doSomethingWith(x)).
duh*_*ime 11
我在渲染函数中遇到了类似的绑定,最终this以下列方式传递了上下文:
{someList.map(function(listItem) {
// your code
}, this)}
Run Code Online (Sandbox Code Playgroud)
我也用过:
{someList.map((listItem, index) =>
<div onClick={this.someFunction.bind(this, listItem)} />
)}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
81826 次 |
| 最近记录: |