React: quot;thisquot; is undefined inside a component function(反应:“这个在组件函数内部未定义)
问题描述
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
应该引用组件.我错过了什么吗?
I want to update loopActive
state on toggle, but this
object is undefined in the handler. According to the tutorial doc, I this
should refer to the component. Am I missing something?
推荐答案
ES6 React.Component
不会自动将方法绑定到自身.您需要在 constructor
中自己绑定它们.像这样:
ES6 React.Component
doesn't auto bind methods to itself. You need to bind them yourself in constructor
. Like this:
constructor (props){
super(props);
this.state = {
loopActive: false,
shuffleActive: false,
};
this.onToggleLoop = this.onToggleLoop.bind(this);
}
这篇关于反应:“这个"在组件函数内部未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:反应:“这个"在组件函数内部未定义
基础教程推荐
- 悬停时滑动输入并停留几秒钟 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 我什么时候应该在导入时使用方括号 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 动态更新多个选择框 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01