【问题标题】:Auto selected of value from options in react-select react从反应选择反应中的选项中自动选择值
【发布时间】:2021-08-16 16:32:23
【问题描述】:

问题陈述:


我使用 react-select 2.4.1 作为 Select 下拉菜单。
我想根据某些条件从选项数组中自动选择值,并且自动选择的值也应该在组件状态下更新,反之亦然。

我怎样才能做到这一点?

我尝试了多种方法,请帮忙。
提前致谢。

下面是我选择下拉菜单的代码。

<Select
  options={props.mercModeOptions}
  onChange={(evt) => setSelectedMercMode(evt.value)}
  selected={props.mercModeDefaultOpt}
/>  

下面是选项数组:

props.mercModeOptions = [
  {
    value: "first", 
    label: "first"
  },
  {
    value: "second",
    label: "second"
  },
  {
    value: "third",
    label: "third"
  }
]

要自动选择的值:

props.mercModeDefaultOpt = {
  value: "third",
  label: "third"
};

【问题讨论】:

  • 第一次渲染 Select 时自动选择的值?
  • @Shyam,我们可以说是第一次。就像直到用户不更改下拉列表中的值,它应该显示自动选择的值。您对我实现这一目标有什么建议吗?

标签: reactjs react-select


【解决方案1】:

我添加了示例codesandBox 来实现这一点。

我们可以使用 useMemo 钩子将默认值存储在变量中并更新本地状态。

import Select from "react-select";
import { useEffect, useMemo, useState } from "react";
const dropDowonData = [
  { value: "first", label: "first" },
  { value: "second", label: "second" },
  { value: "third", label: "third" }
];
export default function App() {
  const [selectedValue, setSelectedValue] = useState();

  // This will run for only during the first render.
  const defaultSelectedValue = useMemo(() => {
    // to update the local state 
    setSelectedValue(dropDowonData[0]);
    
    return dropDowonData[0];
  }, []);

  console.log(selectedValue);

  return (
    <div className="App">
      <Select
        defaultValue={defaultSelectedValue}
        value={selectedValue}
        onChange={(value) => setSelectedValue(value)}
        name="Select"
        options={dropDowonData}
      />
    </div>
  );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-09
    • 2016-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多