如何在 React JS 的下拉列表中设置值?

how to set value in dropdown in react js?

你能告诉我如何在 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 预期输出 奥兰群岛 应该 selected。 { 键:"ax",值:"ax",文本:"Aland Islands" },

三秒后我想select这个元素

const val = "ax";

使用 "value" 属性。

// 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"
  />
);

你应该更新你的问题,因为只有在访问 codesandbox 之后我才能获得足够的信息来回答..

在您的 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}
/>
);

正如 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"
  />
);

您可以将值传递给下拉列表的值 属性。对所选值使用状态 属性。 确保您 change/update 在 onchange 事件上声明。