可以从 reactjs 中的事件处理函数访问选项标签元素的键吗?
Can access a the key of an option tag element from the event handler function in reactjs?
我有一个非常具体和奇怪的情况。
我有足够大的对象数组,用于存储需要从 select 框中 select 编辑的所有对象。
像这样排序:
var optionsArray = [
{
name: option1,
code: f2X
},
{
name: option2,
code: x21
},
...
{
name: option100,
code: Rga
},
]
重点是,代码 属性 与选项的名称没有任何关系。
我目前将其放在 select 框中,在 select 选项之后,我需要 return 该选项的代码。这是 select 框和偶数处理程序当前的样子:
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>
);
}
所以基本上在事件处理程序中我想访问代码而不是我刚刚 select编辑的选项的名称。
我想也许我可以访问我从键 select 编辑的数组的索引,然后做这样的事情:
onChange(e){
console.log ("selected option code", optionsArray[e.target.key].code);
}
但密钥未定义。有什么方法可以从事件中访问 selected 选项的密钥吗?或者更好的是,有没有一种方法可以将代码包含在选项标记中,以便以后可以在事件处理程序中轻松访问它?
您需要在 option
中传递 value
属性,其中将包含代码值。所以它会像
<FormControl componentClass="select" onChange={this.onChange}>
{
optionsArray.map(function(value, key) {
return <option key={key} value={value.code}>{value.name}</option>
})
}
</FormControl>
并在 onChange
函数中像 e.target.value
一样访问它。
onChange(e){
console.log ("option selected", e.target.value);
}
我有一个非常具体和奇怪的情况。
我有足够大的对象数组,用于存储需要从 select 框中 select 编辑的所有对象。
像这样排序:
var optionsArray = [
{
name: option1,
code: f2X
},
{
name: option2,
code: x21
},
...
{
name: option100,
code: Rga
},
]
重点是,代码 属性 与选项的名称没有任何关系。
我目前将其放在 select 框中,在 select 选项之后,我需要 return 该选项的代码。这是 select 框和偶数处理程序当前的样子:
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>
);
}
所以基本上在事件处理程序中我想访问代码而不是我刚刚 select编辑的选项的名称。
我想也许我可以访问我从键 select 编辑的数组的索引,然后做这样的事情:
onChange(e){
console.log ("selected option code", optionsArray[e.target.key].code);
}
但密钥未定义。有什么方法可以从事件中访问 selected 选项的密钥吗?或者更好的是,有没有一种方法可以将代码包含在选项标记中,以便以后可以在事件处理程序中轻松访问它?
您需要在 option
中传递 value
属性,其中将包含代码值。所以它会像
<FormControl componentClass="select" onChange={this.onChange}>
{
optionsArray.map(function(value, key) {
return <option key={key} value={value.code}>{value.name}</option>
})
}
</FormControl>
并在 onChange
函数中像 e.target.value
一样访问它。
onChange(e){
console.log ("option selected", e.target.value);
}