能否请您告诉我如何在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”,文本:“奥兰群岛”},
三秒钟后,我要选择此元素
const val = "ax";
答案 0 :(得分:2)
正如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"
/>
);
答案 1 :(得分:1)
您应该更新您的问题,因为只有在访问了codeandbox之后,我才能获得足够的信息以获取答案。
在index.js中,您应该将setState(countryOptions)更新为:
setState({countryOptions:countryOptions},()=>setState({val:"ax"})
然后在第39行到:
<Example countryOptions={state.countryOptions:countryOptions} val={state.val} />
然后在example.js中将const DropdownExampleClearableMultiple更新为:
const DropdownExampleClearableMultiple = ({ countryOptions, val }) => (
<Dropdown
clearable
fluid
search
closeOnChange
selection
options={countryOptions}
placeholder="Select Country"
value={val}
/>
);
答案 2 :(得分:0)
使用“价值”道具。
// index.js
const App = ({ children }) => {
const val = "ax";
const [state, setState] = useState([]);
setTimeout(() => {
setState(countryOptions);
}, 2000);
return (
<Container style={{ margin: 20 }}>
<Example countryOptions={state} value={val} />
</Container>
);
};
// example.js
const DropdownExampleClearableMultiple = ({ countryOptions, value }) => (
<Dropdown
clearable
fluid
search
closeOnChange
selection
value={value}
options={countryOptions}
placeholder="Select Country"
/>
);
答案 3 :(得分:0)
您可以将Dropdown的value传递给value属性。使用状态属性作为所选值。 确保在onchange事件上更改/更新状态。