反应:“这个"在组件函数内未定义 [英] React: "this" is undefined inside a component function

查看:39
本文介绍了反应:“这个"在组件函数内未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class PlayerControls 扩展 React.Component {构造函数(道具){超级(道具)this.state = {循环活动:假,shuffleActive:假,}}使成为() {var shuffleClassName = this.state.toggleActive ?玩家控制图标激活":玩家控制图标"返回 (<div className="player-controls"><FontAwesomeclassName="玩家控制图标"名称='刷新'onClick={this.onToggleLoop}自旋={this.state.loopActive}/><FontAwesomeclassName={shuffleClassName}名称='随机'onClick={this.onToggleShuffle}/>

);}onToggleLoop(事件){//这是未定义的??"<--- 这里this.setState({loopActive: !this.state.loopActive})this.props.onToggleLoop()}

我想在切换时更新 loopActive 状态,但 this 对象在处理程序中未定义.根据教程文档,我 this 应该指的是组件.我错过了什么吗?

解决方案

ES6 React.Component 不会自动将方法绑定到自身.您需要自己在 constructor 中绑定它们.像这样:

构造函数(道具){超级(道具);this.state = {循环活动:假,shuffleActive:假,};this.onToggleLoop = this.onToggleLoop.bind(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()
  }

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 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);

}

这篇关于反应:“这个"在组件函数内未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆