可以从 reactjs 中的事件处理程序函数访问选项标签元素的键



我有一个非常具体和奇怪的情况。

我有一个足够大的对象数组,它存储了需要从选择框中选择的所有对象。

像这样排序:

var optionsArray = [
   {
      name: option1,
      code: f2X
   },
   {
      name: option2,
      code: x21
   },
   ...
   {
      name: option100,
      code: Rga
   },
]

关键是,代码属性与选项的名称无关。

我目前将其放在选择框中,选择该选项后,我需要返回该选项的代码。以下是选择框甚至处理程序当前的样子:

class SelectForm extends Component{
    onChange(e){
       console.log ("option selected", e.target.name);
       //I can access the name, but what I want to access is the the code
    }
    render(){
        var _this = this;
        return (
            <FormGroup controlId="myId">
                <FormControl componentClass="select" onChange={this.onChange}>
                    {
                      optionsArray.map(function(value, key) {
                      return <option key={key}>{value.name}</option>
                      })
                    }
                </FormControl>
                </FormGroup>
        );
    }

所以基本上在事件处理程序中,我想访问代码而不是我刚刚选择的选项的名称。

我想也许我可以访问我从键中选择的数组的索引,并执行以下操作:

onChange(e){
   console.log ("selected option code", optionsArray[e.target.key].code);
}

但密钥是不确定的。有什么方法可以从事件中访问所选选项的密钥吗?或者更好的是,有没有办法将代码包含在选项标记中,以便以后可以轻松地在事件处理程序中访问它?

您需要

在包含代码值的option中传递value属性。所以它会像

<FormControl componentClass="select" onChange={this.onChange}>
  {
     optionsArray.map(function(value, key) {
         return <option key={key} value={value.code}>{value.name}</option>
     })
  }
</FormControl>

并像e.target.value在您的onChange功能中一样访问它。

onChange(e){
   console.log ("option selected", e.target.value);
}

最新更新