问题
I try to use react-select in my reactjs app, but I have a problem with the onChange event. onChange is supposed to send two arguments. The first is supposed to be the selected value, but instead of the selected value, the whole option item is passed as the selected value.
For instance
- I have an array of option items like
options=[{ id: '1', name: 'A'},{ id: '2', name:'B'}]
- I set
getOptionValue = (i) => i.id;
andgetOptionLabel = (i)=>i.name;
- When select the second item
onChange(value)
is passed the second option as thevalue
argument ({id:'2',name:'B'}
) instead of the value of the second option ('2'
).
This behavior is inconsistent with most input components out there. I would expect onChange
to be passed the value of the item, and for the item itself I would expect another event like onItemSelected
or something like that.
Also, when I set value={'2'}
(controlled component), the component doesn't show the selected item.
I must say that I use AsyncSelect with loadOptions.
How can I make it work with just simple values, instead of option objects?
If this can't happen I have to abandon react-select for another similar component.
回答1:
AFAIK currently there's no way to make React-Select work internally with just the value. What I'm doing in my application is implementing a layer to retrieve the object going down, and extract the value going up. Something like this (this is simplified, you may need more validation or handling depending on your application):
const Select extends Component {
handleChange(newSelected) {
// this.props.handleChange is your own function that handle changes
// in the upper scope and receives only the value prop of the object
// (to store in state, call a service, etc)
this.props.handleChange(newSelected.value);
}
render() {
// Assuming you get the simple value as a prop from your store/upper
// scope, so we need to retrieve the option object. You can do this in
// getDerivedStateFromProps or wherever it suits you best
const { options, value } = this.props;
const selectedOption = options.find(option => option.value === value)
<ReactSelect
options={options}
value={selectedOption}
onChange={this.handleChange}
{...props}
/>
}
来源:https://stackoverflow.com/questions/52938331/how-can-i-work-with-just-values-in-react-select-onchange-event-and-value-prop