简体   繁体   English

仅通过单击即可在反应选择触发器上进行onchange事件

[英]onchange event on react select trigger only by clicking

i have an <select> in my react app 我的应用程序中有一个<select>

<select onChange={ e=>{this.setState({selectedValue:e.target.value})} }>
    {this.state.someArr.map( val => <option value={val}> something </option>) }
</select>

now if someArr in the state changes , it cause the new options rendered inside select element 现在,如果someArr中的someArr更改,它将导致在select元素内呈现新选项
but onchange not triggered and selectedValue inside the state remains untouched 但是onchange不会触发,状态内的selectedValue保持不变
how can i overcome this issue? 我该如何克服这个问题? i want new value to set automatically 我希望自动设置新值

HERE IS JSBIN 这里是JSBIN

First of all, when using React you should never pass an arrow function because it passes different instance each time and can cause unnecessary rendering. 首先,在使用React时,永远不要传递箭头功能,因为它每次都会传递不同的实例,并且可能导致不必要的渲染。

The reason it doesnt work, is because you're trying to access the event in the setState function and you cant do that. 它不起作用的原因是,您试图在setState函数中访问该事件,并且您无法执行该操作。

Here is what you should do: 这是您应该做的:

export default class Component extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            selectedValue: '',
            someArr: []
        };
    }

    onChange(e) {
        let value = e.target.value;
        this.setState({ selectedValue: value });
    }

    render () {
        return <select onChange={this.onChange}}>
                {this.state.someArr.map( val => <option value={val}> something </option>) }
            </select>   
    }
}

All you need to do is set the value prop properly. 您需要做的就是正确设置value prop。

<select value={this.state.selectedValue} onChange={ e=>{this.setState({selectedValue:e.target.value})} }>
    {this.state.someArr.map( val => <option value={val}> something </option>) }
</select>

I hope this works for you. 希望这对您有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM