简体   繁体   English

以编程方式 select 一个带有 react-select 的选项

[英]Programmatically select an option with react-select

I have a basic understanding of React.我对 React 有一个基本的了解。 I'm using react-select and I want to programmatically select an option.我正在使用react-select并且我想以编程方式 select 一个选项。 For example, with the code below, how to select option B on clicking the button?例如,使用下面的代码,如何在单击按钮时 select 选项 B ?

This page mentions a setValue function, but I don't understand how to use it.这个页面提到了一个setValue function,但是我不明白怎么用。 I don't know what is a "ref" in React and how to use it, and I found similar questions on SO with answers assuming this knowledge.我不知道什么是 React 中的“参考”以及如何使用它,我在 SO 上发现了类似的问题,并假设这些知识的答案。

import { useState } from "react";
import Select from "react-select";

const options = [
  { value: "A", label: "A" },
  { value: "B", label: "B" }
];

export default function App() {
  const [selectedOption, setSelectedOption] = useState("A");

  const handleChange = (value) => {
    setSelectedOption(value);    
  };

  return (
    <div className="App">
      <Select
        value={selectedOption}
        onChange={handleChange}
        options={options}
      />
      <button onClick={() => ????????}>Select B</button>
    </div>
  );
}

You can use the following code.您可以使用以下代码。

import { useState } from "react";
import Select from "react-select";

const options = [
  { value: "A", label: "A" },
  { value: "B", label: "B" }
];

export default function App() {
  const [selectedOption, setSelectedOption] = useState(options[0]);

  const handleChange = (value) => {
    setSelectedOption(value);    
  };

  return (
    <div className="App">
      <Select
        value={selectedOption}
        onChange={handleChange}
        options={options}
      />
      <button onClick={() => setSelectedOption(options[1])}>Select B</button>
    </div>
  );
}

React-Select is different with Select from Material UI. React-Select 与 Material UI 中的 Select 不同。 React-Select receives the object of options and set, display the value according to the object. React-Select 接收object的选项并设置,根据object显示值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM