反应:"this"在组件函数中未定义

编程入门 行业动态 更新时间:2024-10-22 15:34:04
本文介绍了反应:"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对象.根据教程文档,我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); }

更多推荐

反应:"this"在组件函数中未定义

本文发布于:2023-11-28 06:55:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641370.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   组件   中未   定义   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!