我在使用选择下拉列表时收到了React的setState中错误的响应。它给了我之前选择的选项的价值。当我第一次选择的东西出现为空白,但第二个选择会给我我之前选择的东西。ReactJS的setState混淆与选择下拉
所以,先挑:“绿色”的结果为空 第二顺位:“红楼梦”给我“GRE”作为结果
我知道我失去了一些东西,也许我没有正确绑定它?
class Main extends React.Component {
constructor(props) {
super(props);
this.state = {
typeValue: ''
}
this.changeHandler = this.changeHandler;
this.expressValue = this.expressValue.bind(this);
}
expressValue(e) {
this.setState({
typeValue : e.target.value
});
console.log('this type val state is: ' + this.state.typeValue);
}
render() {
return (
<div>
<TypeSelect changeHandler={this.expressValue} />
</div>
)
}
};
class TypeSelect extends React.Component {
constructor(props) {
super(props);
}
render() {
let options = {
'default': 'Choose a category',
'red': 'Red',
'blu': 'Blue',
'gre': 'Green',
}
return (
<select name="name_type" id="name_type" onChange={this.props.changeHandler}>
{
Object.keys(options).map(function(key){
return (
<option key={key} value={key}>{options[key]}</option>
)
})
}
</select>
)
}
};
绑定'changeHandler'给了我一个'Uncaught TypeError:无法读取未定义的属性'绑定'的错误。 – SVY
它会在您编写函数时定义。所以上面的expressValue(e){...,如果你写'changeHandler(e){console.log(e)};',this.changeHandler将不再是未定义的。 –
对不起,但我没有看到该组件中的这个功能,也没有在任何地方看到它的用法。你可以删除这一行,这是没用的。 –