如何使用react在材料-ui中从SelectField获取id?

时间:2017-09-21 20:23:52

标签: reactjs material-ui

我已经查看并尝试过其他问题的解决方案,但我似乎无法让它工作。我面临的问题是event.target.id和event.target.value在这里不起作用。我做了一些研究,发现了原因。现在我只需要一种方法来获得" id"来自selectfield

如何获取ID,以使此功能正常工作?

这里我有选择:

          <SelectField
          id="category"
          floatingLabelText="Category"
          value={this.state.value}
          onChange={this.updateTask.bind(this)}
        >
          <MenuItem disabled={true} primaryText="Choose A Category" />
          <MenuItem value="delivery" primaryText="Delivery" />
          <MenuItem value="dog walking" primaryText="Dog Walking" />
          <MenuItem value="house cleaning" primaryText="House Cleaning" />
        </SelectField>

这是功能:

 updateTask(event, index, value) {
    event.preventDefault();
    let updated = Object.assign({}, this.state.task);
    updated[event.target.id] = event.target.value;
    this.setState({
      task: updated,
      value: value,
    });
  }

3 个答案:

答案 0 :(得分:0)

不确定Material-UI的工作原理,但你可以做到

onChange={(event, index, value) => this.updateTask(event, index, value, "id")}

并将id参数添加到updateTask

updateTask(event, index, value, id){
   console.log(id) 
}

答案 1 :(得分:0)

似乎已将其报告为issue on their github

由于某种原因someone implemented the ability传递名称prop而不是id道具。

我自己选择依靠name道具。但是,链接中还提供了一个建议,即暗示访问基础元素。

答案 2 :(得分:0)

不幸的是,无法将JSON对象作为值传递给上述Selects“ onChange”方法,或者-更好的说-可以,但是然后MaterialUI注入存储在MenuItem中的值(现在是JSON) Object)放入SelectMenu的textField中,因此它什么也不显示,因为您不能更改该值的显示方式。因此,就目前而言,据我所知,只能通过event.target.value传递一个参数。如果您需要更多的参数(例如以索引为例),则可以这样完成:

在Select的“ onChange”道具中,接受两个参数:第一个是从中提取值的事件,第二个是被单击的子对象,如此处所述:https://material-ui.com/api/select/

现在,您可以通过child.props.[yourVariable]

访问event.target.value中的值,以及访问子级的任何唯一属性(首先定义)。

在MenuItem的声明中;将您的ID设置为menuItem的道具

 {this.state.availableDays.map((day, i) => {
        return (
              <MenuItem id={i} value={day.key}>{day.key}</MenuItem>
               )
   })}

在Select的“ onChange”方法中;接受事件和孩子作为参数;访问child.props。[yourVariable]

onChange={(event, child) => {this.setState({currentDayString: event.target.value, currentDayIndex: child.props.id}) ,this.displayDataForThisDay() }}

我确实知道这个问题是一年前提出的;但也许我的答案对寻找这个问题的答案的人有帮助

相关问题