我正在尝试从 React 中的以下表单中获取所选选项的列表。
<form onSubmit={ this.handleOptionsSelected.bind(this) }>
<div>
<select multiple>
{ this.getOptionList() }
</select>
</div>
<input type="submit" value="Select"/>
</form>
这是我的handleOptionsSelected
实现。
handleOptionsSelected(event) {
event.preventDefault();
console.log("The selected options are " + event.target.value);
}
但是,我得到了 event.target.value
的 undefined
值。
有人知道如何更正上面的代码吗?
最佳答案
您可以在 <select ref={node => this.select = node} multiple>
中添加一个 ref并循环遍历这些值。
像这样。
class Example extends React.Component{
handleOptionsSelected(event){
event.preventDefault();
const selected = [];
for(let option of this.select.options){
if(option.selected){
selected.push(option.value)
}
}
console.log(selected);
}
render() {
return (
<form onSubmit={ this.handleOptionsSelected.bind(this) }>
<div>
<select ref={node => this.select = node} multiple="true">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
</div>
<input type="submit" value="Select"/>
</form>
)
}
}
ReactDOM.render(
<Example name="World" />,
document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>
关于javascript - 从 React 中的多个选择表单中获取选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43927026/