运行 onchange 事件反应

Run onchange event react

我正尝试在 select-react 组件上 运行 一个 onChange 事件,但我无法更改默认值。 除了更改选项外,我还需要将选择值分配给一个state。 当我删除 state 时,我可以正常更改选项。

我将代码保存在 codesandbox 以供验证。

const options = [
  {
    label: "Queue 1",
    value: 0
  },
  {
    label: "Queue 2",
    value: 1
  },
  {
    label: "Queue 3",
    value: 2
  }
];

const defaultOptions = [
  {
    label: "Queue 1",
    value: 0
  },
  {
    label: "Queue 3",
    value: 2
  }
];

const App = () => {
  const [selectedQueue, setSelectedQueue] = useState([]);

  const handleChange = async (e) => {
    const value = e.map((x) => x.value);
    console.log(value);

    // if you comment the two lines, below I have no problems
    setSelectedQueue(value);
    console.log(selectedQueue);
  };

  const CustomSelect = (props) => (
    <Select
      options={options}
      defaultValue={defaultOptions}
      className="custom-select"
      onChange={handleChange}
      {...props}
    />
  );

  return (
    <div className="App">
      Multiselect:
      <CustomSelect isMulti />
    </div>
  );
};
export default App;

您在每个渲染器上重新创建 CustomSelect 组件,这意味着该组件在每个渲染器上重新安装,并再次应用 defaultValue。从App组件中提取组件(sandbox):

const CustomSelect = (props) => <Select className="custom-select" {...props} />;

然后将 props 传递给组件,当你在 App 中渲染它时:

const App = () => {
  const [selectedQueue, setSelectedQueue] = useState([]);

  const handleChange = async (e) => {
    const value = e.map((x) => x.value);
    console.log(value);

    // if you comment the two lines, below I have no problems
    setSelectedQueue(value);
    console.log(selectedQueue);
  };

  return (
    <div className="App">
      Multiselect:
      <CustomSelect
        options={options}
        defaultValue={defaultOptions}
        onChange={handleChange}
        isMulti
      />
    </div>
  );
};