【问题标题】:React: "this" is undefined inside a component functionReact:“this”在组件函数中未定义
【发布时间】:2015-11-28 16:30:26
【问题描述】:
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 应该指的是组件。我错过了什么吗?

【问题讨论】:

    标签: javascript reactjs this


    【解决方案1】:

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

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

    【讨论】:

    • 如果在将 onToggleLoop 函数移动到反应类后将 onClick 属性更改为 () =&gt; this.onToggleLoop,它也会起作用。
    • 你真的要绑定每一个react类的每一个方法吗?是不是有点疯狂?
    • @AlexL 有一些方法可以在不显式绑定方法的情况下做到这一点。如果您使用 babel,则可以将 React 组件上的每个方法声明为箭头函数。这里有例子:babeljs.io/blog/2015/06/07/react-on-es6-plus
    • 但是为什么this首先是未定义的呢?我知道 Javascript 中的 this 取决于函数的调用方式,但是这里发生了什么?
    • 文章的 TLDR:改用箭头函数。
    【解决方案2】:

    有几种方法。

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

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

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

    【讨论】:

    • 为什么 onToogleLoop = () => {} 有效?我遇到了同样的问题,我在构造函数中绑定了它,但它没有用......现在我看到了你的帖子并用箭头函数语法替换了我的方法,它可以工作。你能给我解释一下吗?
    • 来自developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…;箭头函数不会创建自己的 this,而是使用封闭执行上下文的 this 值。
    • 请注意,onClick 中的内联绑定将在每次渲染时返回一个新函数,因此看起来好像为 prop 传递了一个新值,与 PureComponents 中的 shouldComponentUpdate 混淆了。
    【解决方案3】:

    这样写你的函数:

    onToggleLoop = (event) => {
        this.setState({loopActive: !this.state.loopActive})
        this.props.onToggleLoop()
    }
    

    Fat Arrow Functions

    关键字 this 的绑定在胖箭头函数的外部和内部是相同的。这与使用 function 声明的函数不同,后者可以在调用时将 this 绑定到另一个对象。维护 this 绑定对于映射之类的操作非常方便:this.items.map(x => this.doSomethingWith(x))。

    【讨论】:

    • 如果我这样做,我会得到ReferenceError: fields are not currently supported
    • 如果在构造函数中我说 this.func = () => { ... } 它会起作用,但我认为这有点愚蠢,如果可能的话想避免它。
    • 太糟糕了,你不能在 React 中使用普通的类语法!
    【解决方案4】:

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

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

    我也用过:

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

    【讨论】:

    • 每次渲染列表时,您都在那里创建了很多不必要的功能......
    • @T.J.Crowder 是的,每次调用 render 时都会重新创建这些函数。最好将函数创建为类方法并将它们绑定到类一次,但是对于初学者来说手动上下文绑定可能会有所帮助
    【解决方案5】:

    您应该注意到this 取决于函数的调用方式 即:当函数作为对象的方法调用时,其this 设置为调用该方法的对象。

    this 可在 JSX 上下文中作为组件对象访问,因此您可以将所需的方法内联调用为 this 方法。

    如果你只是传递对函数/方法的引用,react 似乎会将它作为独立函数调用。

    onClick={this.onToggleLoop} // Here you just passing reference, React will invoke it as independent function and this will be undefined
    
    onClick={()=>this.onToggleLoop()} // Here you invoking your desired function as method of this, and this in that function will be set to object from that function is called ie: your component object
    

    【讨论】:

    • 对,您甚至可以使用第一行,即onClick={this.onToggleLoop},前提是您在组件类中定义了一个字段(属性)onToggleLoop = () =&gt; /*body using 'this'*/
    【解决方案6】:

    在我的情况下,这是解决方案 = () => {}

    methodName = (params) => {
    //your code here with this.something
    }
    

    【讨论】:

    • 这是真正的解决方案。忘了把它放在一个让我失望的功能上谢谢
    【解决方案7】:

    如果你使用 babel,你可以使用 ES7 绑定操作符绑定 'this' https://babeljs.io/docs/en/babel-plugin-transform-function-bind#auto-self-binding

    export default class SignupPage extends React.Component {
      constructor(props) {
        super(props);
      }
    
      handleSubmit(e) {
        e.preventDefault(); 
    
        const data = { 
          email: this.refs.email.value,
        } 
      }
    
      render() {
    
        const {errors} = this.props;
    
        return (
          <div className="view-container registrations new">
            <main>
              <form id="sign_up_form" onSubmit={::this.handleSubmit}>
                <div className="field">
                  <input ref="email" id="user_email" type="email" placeholder="Email"  />
                </div>
                <div className="field">
                  <input ref="password" id="user_password" type="new-password" placeholder="Password"  />
                </div>
                <button type="submit">Sign up</button>
              </form>
            </main>
          </div>
        )
      }
    
    }
    

    【讨论】:

      【解决方案8】:

      如果你在生命周期方法中调用你创建的方法,比如componentDidMount...,那么你只能使用this.onToggleLoop = this.onToogleLoop.bind(this)和胖箭头函数onToggleLoop = (event) =&gt; {...}

      在构造函数中声明函数的常规方法不会起作用,因为生命周期方法被更早地调用。

      【讨论】:

        【解决方案9】:

        就我而言,对于使用 forwardRef 接收 ref 的无状态组件,我必须按照这里所说的 https://itnext.io/reusing-the-ref-from-forwardref-with-react-hooks-4ce9df693dd

        从此(onClick 无权访问“this”的等价物)

        const Com = forwardRef((props, ref) => {
          return <input ref={ref} onClick={() => {console.log(ref.current} } />
        })
        

        为此(它有效)

        const useCombinedRefs = (...refs) => {
          const targetRef = React.useRef()
        
          useEffect(() => {
            refs.forEach(ref => {
              if (!ref) return
        
              if (typeof ref === 'function') ref(targetRef.current)
              else ref.current = targetRef.current
            })
          }, [refs])
        
          return targetRef
        }
        
        const Com = forwardRef((props, ref) => {
          const innerRef = useRef()
          const combinedRef = useCombinedRefs(ref, innerRef)
        
          return <input ref={combinedRef } onClick={() => {console.log(combinedRef .current} } />
        })
        

        【讨论】:

          【解决方案10】:

          您可以重写如何从您的 render() 方法调用 onToggleLoop 方法。

          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={(event) => this.onToggleLoop(event)}
                spin={this.state.loopActive}
              />       
            </div>
              );
            }
          

          React documentation 显示了从属性中的表达式调用函数时的这种模式。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2020-03-03
            • 2023-03-18
            • 2017-06-14
            • 1970-01-01
            • 2019-05-29
            • 1970-01-01
            • 1970-01-01
            • 2019-11-04
            相关资源
            最近更新 更多