代码之家  ›  专栏  ›  技术社区  ›  Mizlul

如何存储和访问元素(如React中的select options)上的数据属性

  •  1
  • Mizlul  · 技术社区  · 7 年前

    我想使用react从选项中获取数据属性,但由于某些原因,我无法获取该属性,并且获取空值。

    <select onChange={(e) => this.onIndustryChangeOption(e)} value={this.props.selectedIndustry}>
        <option value="" data-industry="industry1">Select Industry</option>
        <option value="" data-industry="industry2">Select Industry 2</option>
    </select>
    
    onIndustryChangeOption(event, index, value) {
       console.log(event.target.getAttribute('data-industry'));
       this.props.setRootState({selectedIndustry: event.target.value});
    }
    

    这是行不通的,我相信应该有其他方法来做到这一点!

    2 回复  |  直到 7 年前
        1
  •  5
  •   T.J. Crowder    7 年前

    event.target 是吗 select ,而不是 option .你需要拿到 选项 :

    onIndustryChangeOption(event, index, value) {
      const {target} = event;
      const option = target.options[target.selectedIndex];
      if (option) {
        console.log(option.getAttribute('data-industry'));
        //this.props.setRootState({selectedIndustry: event.target.value});
      }
    }
    

    实例:

    class Example extends React.Component {
      render() {
        return <select onChange={(e) => this.onIndustryChangeOption(e)} value={this.props.selectedIndustry}>
            <option value="" data-industry="industry1">Select Industry</option>
            <option value="" data-industry="industry2">Select Industry 2</option>
        </select>;
      }
    
      onIndustryChangeOption(event, index, value) {
        const {target} = event;
        const option = target.options[target.selectedIndex];
        if (option) {
          console.log(option.getAttribute('data-industry'));
          //this.props.setRootState({selectedIndustry: event.target.value});
        }
      }
    }
    
    ReactDOM.render(
      <Example />,
      document.getElementById("root")
    );
    <div id="root"></div>
    <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>

    也就是说,对于给定的示例,不清楚为什么不使用 value 相反。:-)

        2
  •  -2
  •   Zohaib Ijaz    7 年前

    只需传递回调引用和捕获事件,使用 value 属性

    <select onChange={this.onIndustryChangeOption} value={this.props.selectedIndustry}>
        <option value="industry1">Industry 1</option>
        <option value="industry2" >Industry 2</option>
    </select>
    
    onIndustryChangeOption(event) {
       this.props.setRootState({selectedIndustry: event.target.value});
    }