你能告诉我如何在 React JS 的下拉列表中设置值吗? 我在 3000 秒后得到下拉数据,然后我需要在下拉菜单上设置值
const App = ({ children }) => {
const val = "ax";
const [state, setState] = useState([]);
setTimeout(() => {
setState(countryOptions);
}, 2000);
return (
<Container style={{ margin: 20 }}>
<Example countryOptions={state} />
</Container>
);
};
https://codesandbox.io/s/semantic-ui-example-utev4 预期输出 应选择奥兰群岛。 { key: "ax", value: "ax", text: "Aland Islands"},
三秒后我想选择这个元素
const val = "ax";
最佳答案
正如 stavros 所建议的那样;最好在 App 组件中保留状态并将 setVal 传递给下拉列表:
应用:
const App = ({ children }) => {
const [state, setState] = useState([]);
//added val and setVal in App state
const [val,setVal]=useState('ax');
setTimeout(() => {
setState(countryOptions);
}, 2000);
return (
<Container style={{ margin: 20 }}>
//pass val and setVal so dropdown can set val on change
<Example countryOptions={state} val={val} onChange={setVal}/>
</Container>
);
};
下拉列表:
const DropdownExampleClearableMultiple = ({ countryOptions,val,onChange }) => (
<Dropdown
clearable
fluid
search
closeOnChange
selection
options={countryOptions}
//set value to passed in val
value={val}
//use setVal that was passed in as onChange
onChange={(_,i)=>onChange(i.value)}
placeholder="Select Country"
/>
);
关于javascript - 如何在 React JS 的下拉列表中设置值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57622068/