如何从元素中得到"关键"?

jim*_*mmy 24 javascript reactjs

我想在选择更改时获得选项的值和键.

我知道我可以onChangeevent.target.value函数中使用选项的简单值,但是如何获得键?

<select onChange={this.onChangeOption} value={country}>
    {countryOptions.map((item, key) =>
        <option key={key} value={item.value}>
            {item.name}
        </option>
    )}
</select>
Run Code Online (Sandbox Code Playgroud)

Nai*_*han 28

您需要将key中的值作为不同的prop传递.

来自docs:

键用作React的提示,但它们不会传递给您的组件.如果组件中需要相同的值,请将其明确地作为具有不同名称的prop传递:

阅读:https://reactjs.org/docs/lists-and-keys.html

  • 这是一个不好的答案。它没有提出解决方案,也没有考虑到他正在处理本机的“ select”字段,因此该字段可能以某种形式使用,如果替换为自定义组件,该字段可能会损坏 (3认同)
  • 是的,就是这个意思。 (2认同)

Agn*_*ney 25

传递密钥作为支柱显然可以,但更快的方法是将密钥作为自定义属性包含在html中.

class App extends React.Component {
  constructor(props) {
    super(props);
    this.onSelect = this.onSelect.bind(this);
  }
  onSelect(event) {
    const selectedIndex = event.target.options.selectedIndex;
        console.log(event.target.options[selectedIndex].getAttribute('data-key'));
  }

  render() {
    return ( 
      <div>
      <select onChange = {this.onSelect}>
       <option key="1" data-key="1">One</option> 
       <option key="2" data-key="2">Two</option>             </select> 
     </div>
    );
  }
}

ReactDOM.render( < App / > , document.getElementById('root'));
Run Code Online (Sandbox Code Playgroud)
<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="root"></div>
Run Code Online (Sandbox Code Playgroud)

  • 这里的selectedIndex是什么?`event.target.options.selectedIndex`; (2认同)

Val*_*tin 6

执行此操作的一个简单方法是:

const functionCall = (event) => {
    console.log(event.target.getAttribute('a-key'));
}

<button a-key={1} onClick={functionCall}>Press Me</button>

Run Code Online (Sandbox Code Playgroud)

我放了 onClick 但你可以使用任何事件。