反应中无法获取material-ui SelectField的属性

McG*_*ady 5 reactjs material-ui

我正在为我的反应项目使用Material-ui 的SelectField。我从这个答案中尝试了很多方法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>
Run Code Online (Sandbox Code Playgroud)

更新

我试过SelectField不用form,还是无法获取id属性。真是搞糊涂了。

Oli*_*r.h 0

在主组件上,您定义一个用于选择表单组件的道具名称,假设您的城市组件名为: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>
);
}
}
Run Code Online (Sandbox Code Playgroud)

在你的主要组件中,你会说(代码被删除,某些部分被省略)

handleSelectChange(e, index, value, name){
      this.setState({
      [name] : value,
    });
  }

render(){ 
 return (
  <cityForm cityName = "city1"  city={this.state.city1} selectChange={this.handleSelectChange}/>
  );
 }
}
Run Code Online (Sandbox Code Playgroud)

我正在构建一个动态表单生成器,它对我有用=)。