Javascript 如何从 React 元素(更改时)获取“关键”道具?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47070997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:43:26  来源:igfitidea点击:

How to get "key" prop from React element (on change)?

javascriptreactjs

提问by jimmy

I want to get option's value and key when select onChange.

我想在 select 时获取选项的值和键onChange

I know I can get option's valuesimplicity used event.target.valuein onChangeOptionfunction, but how can I get key?

我知道我能得到期权的价值用简单event.target.valueonChangeOption功能,但我怎么能得到key

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

回答by Naisheel Verdhan

You will need to pass value in key as a different prop.

您需要将键中的值作为不同的道具传递。

From docs:

从文档:

Keys serve as a hint to React but they don't get passed to your components. If you need the same value in your component, pass it explicitly as a prop with a different name:

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

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

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

回答by Agney

Passing key as a prop works obviously, but much quicker way could be to include the key as a custom attribute in your html.

将键作为道具传递显然是有效的,但更快的方法可能是将键作为自定义属性包含在您的 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'));
<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>

回答by caesay

So you do need to pass the key into the <option>as a prop, but since the <select>is a native field and handles changes internally it gets a little hard to get that key value back out. Lets start one issue at a time, passing the prop into the option could be as simple as wrapping the option component like so and using the indexprop as the new key prop.

因此,您确实需要将键<option>作为道具传递给,但是由于<select>是本机字段并在内部处理更改,因此很难将键值取回。让我们一次开始一个问题,将 prop 传递到 option 可以像这样包装 option 组件并使用indexprop 作为新的 key prop 一样简单。

const CustomOption = ({ value, children, index }) => (
    <option key={index} value={value}>{value}</option>
);

Also note that we're creating a custom component wrapper above to swallow the indexprop from being applied to <option />itself as react doesnt like unknown props on dom elements.

另请注意,我们在上面创建了一个自定义组件包装器,以将indexprop 应用于<option />自身,因为 react 不喜欢 dom 元素上的未知 props。

Now if we could handle the selected event inside the option we would be done, but we can't do that. so we need to make a custom select as well:

现在,如果我们可以处理选项内的选定事件,我们就可以完成,但我们不能那样做。所以我们还需要进行自定义选择:

class CustomSelect extends React.Component {

    static propTypes = {
        value: PropTypes.object,
        onChange: PropTypes.func,
    }

    handleChanged = (e) => {
        const newValue = e.target.value;
        let newKey;

        // iterate through our children searching for the <CustomOption /> that was just selected
        React.children.forEach(this.children, (c) => {
            if (c.props && c.props.index && c.props.value === newValue) {
                newKey = c.props.key;
            }
        });

        this.props.onChange(e, newKey);
    }

    render() {
        return (
            <select value={this.props.value} onChange={this.handleChanged}>
                {this.props.children}
            </select>
        );
    }
}

it has two props value, and onChange. Notice that we intercept the change event in order to find the index (the key) and we pass it along to the parent as the second parameter. This is not very nice but I can't think of another easy way to do this while still using the native <select>element.

它有两个道具value, 和onChange。请注意,我们拦截更改事件以找到索引(键),并将其作为第二个参数传递给父级。这不是很好,但我想不出另一种简单的方法来做到这一点,同时仍然使用本机<select>元素。

Note you need to replace your usages of <select>and <optoin>to use these new classes, and assign the indexprop along with the keyprop on the option.

请注意,您需要替换对这些新类的使用<select><optoin>使用,并在选项上分配index道具和key道具。

回答by Sreeragh A R

You can pass anything through value. I think this solves your problem.

你可以通过任何东西value。我认为这可以解决您的问题。

<select onChange={this.handleChange}>
        {this.state.countryOptions.map((item, key) =>
          <option key={key} 
            value={JSON.stringify({key, value:item.value})}>
            //passing index along with value
            {item.value}
          </option>
        )}
</select>

handleChange(e) {
    let obj = JSON.parse(e.target.value) 
   // gives object{ key:country index, value: country value}
  }

回答by vsync

Imagine a component like this:

想象一个这样的组件:

<Component data={[{id:'a23fjeZ', name="foo"}, ...]}` 

Which renders a list of inputs, and gets in a dataprop which is a collection (Arrayof Objects):

这使得输入列表,并在获得data道具这是一个集合(数组对象):

function Component ( props ){
    // cached handler per unique key. A self-invoked function with a "cache" object
    const onChange = (cache => param => {
        if( !cache[param] )
            cache[param] = e => 
                console.log(param, e.target.name, e.target.value)

        return cache[param];
    }
    )({});

    return props.data.map(item =>
        <input key={item.id} name={item.name} onChange={onChange(item.id)} />
    }

}

As you can see, the keyisn't being accessed, but is passed into a currying functionwhich is handling the caching internally, to prevent "endless" creation of functions on re-renders.

正如您所看到的,key没有被访问,而是被传递到一个内部处理缓存的柯里化函数中,以防止在重新渲染时“无休止地”创建函数。