我想获取所选选项中的 name
属性值。我怎样才能得到它?
constructor(props) {
this.onChangeField = this.onChangeField.bind(this);
}
onChangeField(e) {
const value = e.target.value;
const name = e.target.name;
console.log(value) // 1234
console.log(name). // no value printed
}
render() {
return (
<div>
<select onChange={this.onChangeField}>
<option name='abcd' value ='1234' key='1234'>Option 1</option>
<option name='wxyz' value ='9876' key='9876'>Option 2</option>
</select>
</div>
)
}
最佳答案
您需要对所选选项的引用。现在你有e.target
这是 <select>
onChangeField(e) {
const select = e.target;
const selectedOption = select.options[select.selectedIndex]; // there are a few ways to do this
const value = select.value; // or selectedOption.value, the select gets the value property of its selected option
const name = selectedOption.name;
console.log(value); // 1234
console.log(name); // should be correct
}
关于javascript - 在 onChange 事件内的选项中获取名称 Prop 的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67989968/