我正在使用SelectField我的 React 项目的material-ui。 我从这个答案Can't get the target attributes of material-ui select react component 尝试了很多方法.
但它们不起作用。我的 target.id
始终等于 ""
如何获取属性(例如 id
)。
这是我的代码:
constructor(props) {
super(props);
this.state = {
form: {
resident_city: ''
},
ret_code: '',
ret_msg: ''
};
this.handleList = this.handleList.bind(this);
}
handleList(event, index, value) {
event.persist()
const field = event.target.id;
const form = this.state.form;
form[field] = value;
console.log(event, value)
this.setState({
form
});
console.log(form);
}
<form>
<SelectField
style={style}
id="city"
value={this.state.form.resident_city}
onChange={this.handleList}
maxHeight={200}
>
{cities}
</SelectField>
</form>
<小时/>
更新
我尝试在没有 form
的情况下使用 SelectField
,但仍然无法获取 id
属性。这真的让我很困惑。
最佳答案
在主组件上,您定义一个用于选择表单组件的 Prop 名称,假设您的城市组件名为:cityForm
在你的 cityForm 组件中
render() {
return (
<SelectField
style={style}
value={this.props.city}
onChange={(e, index, value) => this.props.selectChange(e, index, value, this.props.cityName)}
maxHeight={200}
>
{cities}
</SelectField>
);
}
}
在您的主要组件中,您将不得不说(代码被删除,省略了某些部分)
handleSelectChange(e, index, value, name){
this.setState({
[name] : value,
});
}
render(){
return (
<cityForm cityName = "city1" city={this.state.city1} selectChange={this.handleSelectChange}/>
);
}
}
我正在构建一个动态表单生成器,它对我有用 =)。
关于reactjs - 无法在react中获取material-ui SelectField的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42902791/