React:访问 <option> 标签中的数据属性

React: access data-attribute in <option> tag

我有这个 select JSX:

    <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.dataset 是 [=14= 的数据集] 标签而不是选择的选项标签:

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

这个问题有解决办法吗?

谢谢

我认为最好的选择是使用 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
    ...
},

我会只传递鼻涕虫:

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

...然后使用 slug 检索数据:

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);
}

(如果不支持 ES6,您可以将 .find 替换为 forEach 或您使用的任何 JS。)

我发现@bjfletcher 比我的更优雅,但我会报告记录:

我在 onChange 方法中通过 e.target.options[e.target.selectedIndex] 访问 <option> DOM 元素:

  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);
  },

虽然不确定兼容性。