【发布时间】:2017-01-23 00:49:19
【问题描述】:
所以我开始将我的应用程序从 ES2015 转换为使用 React 的 ES6。
我有一个父类和一个像这样的子类,
export default class Parent extends Component {
constructor(props) {
super(props);
this.state = {
code: ''
};
}
setCodeChange(newCode) {
this.setState({code: newCode});
}
login() {
if (this.state.code == "") {
// Some functionality
}
}
render() {
return (
<div>
<Child onCodeChange={this.setCodeChange} onLogin={this.login} />
</div>
);
}
}
儿童班,
export default class Child extends Component {
constructor(props) {
super(props);
}
handleCodeChange(e) {
this.props.onCodeChange(e.target.value);
}
login() {
this.props.onLogin();
}
render() {
return (
<div>
<input name="code" onChange={this.handleCodeChange.bind(this)}/>
</div>
<button id="login" onClick={this.login.bind(this)}>
);
}
}
Child.propTypes = {
onCodeChange: React.PropTypes.func,
onLogin: React.PropTypes.func
};
但是这会导致以下错误,
this.state 未定义
指的是,
if (this.state.code == "") {
// Some functionality
}
知道是什么原因造成的吗?
【问题讨论】:
-
你绑定的是你孩子的
login函数,而不是你父母的。 -
有几种方法可以修复它,主要思想是将
this绑定到回调函数。我有另一个类似帖子的答案,请参考stackoverflow.com/questions/29577977/…
标签: reactjs ecmascript-6 es6-class