I'm using the react-select component in a React app pretty heavily. I've created a wrapper component which allows me to specify a use-case where I want the selected value to reset on selection.
My component wrapper is defined as:
import React, { useRef } from 'react';
import Select from 'react-select'
export const SelectComponent = (props) => {
const selectRef = useRef(null);
const valueSelected = (item) => {
if (!item || item.value === props.selectedValue) {
return;
}
if (props.resetOnSelect) {
selectRef.current.select.clearValue();
}
props.onValueSelected(item);
}
return <div className="modal-form-row">
<Select ref={selectRef} options={props.options} onChange={valueSelected} id={props.id} isClearable={true} isSearchable={true} placeholder={props.label} value={props.selectedValue} />
</div>;
}
And this is how the component gets referenced:
const options = [
{ label: 'Item1', value: '1' },
{ label: 'Item2', value: '2' },
{ label: 'Item2', value: '2' },
];
<SelectComponent id="select-list" label="Pick an Item" options={options} onValueSelected={this.handleNewItem} value="" resetOnSelect={true} />
It appears to be working, as my valueSelected
handler is called a second time with a null argument, but the select component itself doesn't re-render, it leaves the user's selection showing. Any ideas on what I should try next?
question from:
https://stackoverflow.com/questions/65941267/programmatically-change-the-value-of-react-select-component 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…