你能告诉我如何在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
预期产量
奥兰群岛应选择。
{键:“ ax”,值:“ ax”,文本:“ Aland Islands”},
因为三秒钟后我想选择此元素
const val = "ax";
最佳答案
正如斯塔夫罗斯回答所暗示的那样;最好将状态保留在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"
/>
);