2017-08-27 87 views
1
countries() 
{ 
    return [{"name":"Afghanistan","code":"AF"},{"name":"Albania","code":"AL"},...]; 
} 

handleCountryChange(e) 
{ 
    console.log('NAME -> ' + e.target.value, ', CODE -> ' + e.target.id); 
    // Outputs: NAME -> Afghanistan, CODE -> country  
} 

render() 
{ 
    return (
     <select className="form-control country-name" id="country" 
     onChange={e => this.handleCountryChange(e)} > 

      {countries().map((country, i) => { return ( 
       <option id={country.code} value={country.name} key={i} > 
        {country.name} 
       </option> 
      )})} 
     </select> 
    ); 
} 

對select元素使用onChange處理程序時,我試圖檢索選項的屬性。 country codecountry name分別存儲在其id和value屬性中。我得到以下結果獲取選擇字段中選定選項的屬性

輸出:名稱 - >阿富汗,CODE - >國家

這意味着我得到來自所選擇的選項選擇元素的值和標識。如何從其上發生的事件中檢索活動<option>元素的屬性,而不是select元素本身?

回答

0

寫這樣獲得所選項目的屬性:

handleCountryChange(e){ 
    let index = e.target.selectedIndex; 
    let el = e.target.childNodes[index] 
    let option = el.getAttribute('id'); 
    console.log('Name, Code', e.target.value, option); 
} 

檢查這個例子:

let data = [{a:1, b:'a'}, {a:2, b:'b'}, {a:3, b:'c'}]; 
 

 
class App extends React.Component{ 
 

 
\t handleCountryChange(e){ 
 
\t  let index = e.target.selectedIndex; 
 
\t  let el = e.target.childNodes[index] 
 
\t  let option = el.getAttribute('id'); 
 
\t  console.log('Name, Code', e.target.value, option); 
 
\t } 
 

 
\t render(){ 
 
\t  return (
 
\t   <select 
 
\t   \t id="country" 
 
\t   \t onChange={e => this.handleCountryChange(e)} > 
 
\t    \t { 
 
          data.map((country, i) => <option id={country.b} value={country.a} key={i} > {country.a} </option>) 
 
\t    \t } 
 
\t   </select> 
 
\t ); 
 
\t } 
 
} 
 

 
ReactDOM.render(<App/>, document.getElementById('app'))
<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='app'/>

2

您可以在值發送整個對象一個使用選定對象的所有屬性的選項。

getValue(e) { 
 
    console.log(JSON.parse(e.target.value)); 
 
    } 
 

 
    render() { 
 

 
    let cc = [{ 
 
    value: '1st', 
 
    id: 1 
 
    }, 
 
    { 
 
    value: '2nd', 
 
    id: 2 
 
    }] 
 
    
 
    <select onChange={e => this.getValue(e)}> 
 
      <option value={JSON.stringify(cc[0])}>One</option> 
 
      <option value={JSON.stringify(cc[1])}>Two</option> 
 
</select> 
 
}

希望這將在未來幫助有類似問題

+0

那太好了。將整個對象發送到元素的值是絕對實用的。謝謝,Kochar。 – anonym

相關問題