简体   繁体   English

使用ES6类的React组件中的此对象

[英]this object in React Component using ES6 classes

I have a MsgInput component with a textarea which onKeyUp triggers a handler function. 我有一个带有textareaMsgInput组件,其中onKeyUp触发了一个处理函数。 Inside the handler function, I try reading the props using this.props , but not sure why props is undefined here. 在处理函数内部,我尝试使用this.props读取道具,但不确定为什么道具在这里未定义。 Ofcourse the workaroud is to use this.handler.bind(this) . 当然,workaroud是使用this.handler.bind(this)

export class MsgInput extends React.Component {
  constructor(props) {
        super(props);
  }

  inputHandler(e) {
    if(e.keyCode == 13 && !e.shiftKey) {
      this.props.onNewMessage({content: e.target.value});
      e.target.value = '';
      e.preventDefault();
    }
  }

  render() {
    return (
        <div className="controls">
            <textarea onKeyDown={this.inputHandler.bind(this)} className="msg-input" placeholder="Write something" disabled={!this.props.auth}></textarea>
        </div>
    );
  }
}

React with ES6 classes doesn't auto bind your callbacks to the component instance, so you have to do it yourself as you already did. 与ES6类进行反应不会自动将回调绑定到组件实例,因此您必须自己执行此操作。 Otherwise this would not available in the callback. 否则, this将在回调中不可用。


this.inputHandler.bind(this)

This is not a work around, but the way it is supposed to be. 这不是一种解决方法,而是应该采用的方式。

Another alternative is to utilise ES6 arrow functions which would automatically bind this . 另一种方法是使用ES6箭头功能,它会自动绑定this

<textarea onKeyDown={(e) => this.inputHandler(e)}></textarea>

Caveat: Using .bind or arrow function inside your jsx will create a new function on every render which is a performance impediment. 警告:在jsx中使用.bind或箭头函数将在每个渲染上创建一个新功能,这是一个性能障碍。

As a last resort you can bind methods in your constructor which wouldn't have the performance penalty of arrow functions. 作为最后的手段,您可以绑定构造函数中的方法,这些方法不会对箭头函数造成性能损失。

constructor(props) {
    super(props);
    this.inputHandler = this.inputHandler.bind(this);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM