簡體   English   中英

從React中的多個選擇表單中獲取選項

[英]Get options from multiple select form in React

我正在嘗試從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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM