Ben*_*man 1 reactjs react-select material-ui
我通过 React Select 有两个选择输入。我的第二个选择的 options 属性应该根据第一个反应选择中的值动态变化。做这个的最好方式是什么?
我的第一个选择:
<Select
styles={colourStyles}
className="basic-single"
classNamePrefix="select"
isClearable={isClearable}
isSearchable={isSearchable}
placeholder="Select service category"
name="color"
options={serviceCategoriesPrimary}
onChange={(value) =>
value !== null ? setSelectValue(value.value) : setSelectValue("")
}
/>
Run Code Online (Sandbox Code Playgroud)
我的第二个选择:
<Select
styles={colourStyles}
className="basic-single"
classNamePrefix="select"
isClearable={isClearable}
isSearchable={isSearchable}
isDisabled={selectValue === "" ? true : false}
placeholder="Select secondary category"
name="color"
options={handleChooseOptions}
/>
Run Code Online (Sandbox Code Playgroud)
const handleChooseOptions = () => {
if(selectValue === 'Health Care'){
return options1
}else{
return options2
}
}
Run Code Online (Sandbox Code Playgroud)
如果你的optionsFunction比你的示例显示的更复杂,我会记住它的输出optionsFunction并将其作为道具传递给第二个选择。
optionsFunction每次更改都会重新运行selectValue。
重新运行时optionsFunction,它将更新对 select2Options 的引用,重新呈现第二个选择。
const [selectValue, setSelectValue] = useState(null);
const select2Options = useMemo(() => {
if(selectValue === 'Health Care')
return options1 // update pointer
return options2 // update pointer
}, [selectValue]) // rerun function in useMemo on selectValue changes
return (
<>
<Select
{/* will change the dependency of useMemo, re-running the `optionsFunction`, and updating the reference of `select2Options` if necessary */}
onChange={value => setSelectValue(value)}
></Select>
<Select options={select2Options}></Select>
</>
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10462 次 |
| 最近记录: |