【发布时间】:2017-10-04 07:10:18
【问题描述】:
在我的React 代码中,要创建一个闭包,我调用“onChange”
class CityInput extends React.Component {
constructor( props ){
super( props );
this.state = {
city : "",
country : ""
};
this.setChangeType = this.setChangeType( this );
this.onChange = this.onChange.bind( this );
}
setChangeType( cityOrCountry ){
return this.onChange;
}
onChange( e ){
console.log( "e.target.value", e.target.value );
this.setState({
[ cityOrCountry ] : e.target.value
})
}
...
render(){
return(
<form onSubmit = { this.onEnter }>
<label>
City :
<input type = "text"
name = "cityName"
placeholder = "london"
value = { this.state.city }
// the following line executes 'setChangeType' on render,
// which is suppose to return 'onChange' func, ready to be
// executed once the onChange is fired by the user.
// However, thats not happening right now, the function
// 'onChange' is also fired by 'setChangeType' & I
// get the error : 'e.target is undefined'
onChange = { this.setChangeType( "city" )} />
</label>
.... // rest of form
</form>
);
}
};
出于某种原因,我不明白,函数 'this.setChangeType("city")' 被正确触发,但是,onChange 也被触发,而不是返回函数 'onChange'。我做错了什么?
我收到控制台错误:“e.target is undefined”
【问题讨论】:
标签: javascript class reactjs closures