我有以下 React 组件:
class Form extends React.Component {
handleSubmit(e) {
e.preventDefault();
let loginInput = ReactDOM.findDOMNode(this.refs.login);
// change Main component's state
this.props.addCard(loginInput.value);
// reset the form
loginInput.value = '';
}
render() {
return(
<form onSubmit={this.handleSubmit}>
<input placeholder="githug login" ref="login" />
<button>Add Login</button>
</form>
);
}
}
正如你所看到的,我想要handleSubmit
每当提交表单时调用的函数。我已经通过将函数添加到onSubmit
处理程序。
该函数正在正确的时间被调用。然而,价值this
该函数内是null
。这让我感到惊讶,因为我预期的是this
成为 React 组件。事实是this
is null 让我感到惊讶,因为我使用的是非常相似的逻辑/代码,如建议的那样官方 React 文档 https://facebook.github.io/react/docs/forms.html.
我将不胜感激帮助找出原因this
不是React组件,正如预期的那样,以及如何修复代码以使其成为React组件。
当你使用React
with ES2015 classes https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes你应该设置this
到事件处理程序
class Form extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
let loginInput = this.refs.login;
this.props.addCard(loginInput.value);
loginInput.value = '';
}
render() {
return(
<form onSubmit={ this.handleSubmit }>
<input placeholder="githug login" ref="login" />
<button>Add Login</button>
</form>
);
}
}
Example https://jsfiddle.net/69z2wepo/29486/
No Autobinding https://facebook.github.io/react/docs/reusable-components.html#no-autobinding
方法遵循与常规 ES6 类相同的语义,这意味着
他们不会自动将 this 绑定到实例。你必须
显式使用 .bind(this) 或箭头函数 =>。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)