2016-02-19 31 views
4

訪問數據屬性我有這樣的select JSX:陣營:在<option>標籤

<select className="form-control" onChange={this.onChange} value={this.props.value}> 
     {options} 
    </select> 

與選擇之中:

var options = this.props.options.map((option) => { 
    return (<option key={option.slug} value={option.slug} data-country={option.country} data-continent={option.continent}>{option.value}</option>); 
}); 

但我不能訪問該選項的選擇data-country選擇,因爲值是由e.target.value訪問的,並且e.target.datasetselect標記的數據集,而不是選項標記:

onChange: function(e) { 
    this.props.onChange(this.props.name, e.target.value, e.target.dataset.continent, e.target.dataset.country); 
    }, 

有沒有解決這個問題?

感謝

回答

4

我會繞過只是毛坯:

var options = this.props.options.map(option => { 
    return (
     <option key={option.slug} value={option.slug}> 
      {option.value} 
     </option> 
    ); 
}); 

...然後用塞檢索數據:

onChange: function(event, index, value) { 
    var option = this.props.options.find(option => option.slug === value); 
    this.props.onChange(this.props.name, value, option.continent, option.country); 
} 

(你」 d用forEach或任何JS代替.find如果不能夠ES6 u使用)

0

我認爲最好的辦法是使用refs

var options = this.props.options.map((option) => { 
    return (<option ref={'option_ref_' + option.slug} ...></option>); 
}); 

onChange: function(e) { 
    var selectedOption = this.refs['option_ref_' + e.target.value]; 
    selectedOption['data-country']; //should work 
    ... 
}, 
8

我覺得@bjfletcher甚至比我更優雅,但我會爲記錄報告:

我通過e.target.options[e.target.selectedIndex]訪問<option> DOM元素在onChange方法:

onChange: function(e) { 
    var dataset = e.target.options[e.target.selectedIndex].dataset; 
    this.props.onChange(this.props.name, e.target.value, dataset.continent, dataset.country); 
    }, 

雖然不確定兼容性。

+0

這真是太棒了,總是喜歡直接JS獲得選項。有人可以說這條線比'e.target.options [e.target.selectedIndex]'更長,但相信我,這種方法在任何瀏覽器中都可以使用 - 本機支持。 –