【问题标题】:React: access data-attribute in <option> tagReact:访问 <option> 标签中的数据属性
【发布时间】:2016-02-22 17:33:31
【问题描述】:

我有这个selectJSX:

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

有解决办法吗?

谢谢

【问题讨论】:

    标签: reactjs custom-data-attribute


    【解决方案1】:

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

    我在onChange方法中通过e.target.options[e.target.selectedIndex]访问&lt;option&gt; 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);
      },
    

    但不确定兼容性。

    【讨论】:

    • 这真是太棒了,总是喜欢直接 JS 访问选项。有人可能会说这条线更长 e.target.options[e.target.selectedIndex],但相信我,伙计们,这种方法适用于任何浏览器 - 原生支持。
    • 也在 React 17 中工作。
    【解决方案2】:

    我只会绕过蛞蝓:

    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。)

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2020-09-09
        • 1970-01-01
        • 2017-09-17
        • 1970-01-01
        • 2011-04-03
        • 2020-03-08
        • 2011-10-18
        • 2022-01-19
        • 2020-02-08
        相关资源
        最近更新 更多