如何在 react-select 中使用 selectedOption

How to use selectedOption in react-select

我使用 react-select 并且我 new.I 有一个名为 Example 的组件可以正确执行 handleChange 方法

const colourOptions = [
  { value: '1', label: '1', color: '#00B8D9' },
  { value: '2', label: '2', color: '#0052CC' },
  { value: '3', label: '3', color: '#5243AA' },
];

class Example extends React.Component {
  state = {
    selectedOption: null,
  }

  handleChange = (selectedOption) => {
    this.setState({ selectedOption });
    console.log(selectedOption)
  }

  render() {
    const { selectedOption } = this.state;
    return (
        <Select
          value={selectedOption}
          onChange={this.handleChange}
          options={colourOptions}
        />
    );
  }
}

export default Example;

在另一个文件中我们有一个按钮

export default function UserProfile() {
  return (
    <div>

      <Example1/>
      <Example2/>
      <Example3/>

      <Button type="Submit">Search</Button>

    </div>
  );
}

如何通过单击按钮显示 selectedOption 的值?

正确的方法是在parent(UserProfile)中维护selectedOption和handleChange,并将它们传递给child(Example)。

用户配置文件组件

export default function UserProfile() {
  const [selectedOption, setSelectedOption] = useState({});

  const handleChange = (selectedOption) => {
    setSelectedOption(selectedOption)
    console.log(selectedOption)
  };

  const handleClick = () => {
    console.log(selectedOption);      
  };

  return (
    <div>

      <Example onHandleChange={handleChange} selectedOption={selectedOption}/>

      <Button onClick={handleClick} type="Submit">Search</Button>

    </div>
  );
}

示例组件

class Example extends React.Component {

  render() {
    const { selectedOption, onHandleChange } = this.props;

    return (
        <Select
          value={selectedOption}
          onChange={onHandleChange}
          options={colourOptions}
        />
    );
  }
}

export default Example;