es6类中的reactjs'this'上下文

阿比

es6的ReactJS处理方式与类内部方法中的this关键字的上下文混淆

这给出了一个错误,无法获取未定义的引用

class AddItem extends React.Component {
    constructor() {
        super();
    }
    addIt(e) {
        e.preventDefault();
        let newItem = {
            title: this.refs.title.value
        }
        this.refs.feedForm.reset();
        this.props.addItem(newItem);
    }
    render() {
        return (
            <div>
              <form ref="feedForm" onSubmit={this.addIt}>
                <div className="input-group">
                  <span className="input-group-addon"><strong>Title:</strong></span>
                  <input ref="title" type="text" className="form-control" />
                </div>
                <button className="btn btn-success btn-block">Add Item</button>
              </form>
            </div>
        );
    }
}

但这似乎很好

class AddItem extends React.Component {
    constructor() {
        super();
        this.addIt = function(e) {
            e.preventDefault();

            let newItem = {
                title: this.refs.title.value
            }

            this.refs.feedForm.reset();
            this.props.addItem(newItem);
        }.bind(this)
    }

    render() {
        return (
            <div>
              <form ref="feedForm" onSubmit={this.addIt}>
                <div className="input-group">
                  <span className="input-group-addon"><strong>Title:</strong></span>
                  <input ref="title" type="text" className="form-control" />
                </div>
                <button className="btn btn-success btn-block">Add Item</button>
              </form>
            </div>
        );
    }
}

我在第一个做错了什么

Oleksandr T.

当您使用ES6类创建React组件时,您需要手动绑定this事件处理程序,

class AddItem extends React.Component {
  constructor() {
    super();
  }

  addIt(e) {
     // other code
  }

  render() {
    return <div>
      <form ref="feedForm" onSubmit={this.addIt.bind(this)}>
        // other code
      </form>
    </div>
  }
}

或者更好的设置thisconstructor

class AddItem extends React.Component {
  constructor() {
    super();
    this.addIt = this.addIt.bind(this);
  }
  // other code
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章