如何在react js的下拉列表中设置值?

IT技术 javascript reactjs semantic-ui-react
2021-05-01 06:41:33

你能告诉我如何在 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";
4个回答

正如斯塔夫罗斯的回答所建议的那样;最好在 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"
  />
);

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

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

使用“value”props。

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

您可以将值传递给 Dropdown 的 value 属性。对选定值使用状态属性。确保在 onchange 事件上更改/更新状态。