在 react-select 中获取 selected 值 onChange

Get selected value onChange in react-select

我正在使用 react-select 包并使用自定义选项数组来填充数据(即自定义标签等)

我见过几个解决方案,他们没有使用 options 属性来设置值,或者只是使用默认数组模式来填充数据并设置 value 并获取它 onChange,但是我无法在我的情况下获取值:

我是 React 的新手,我肯定不是很了解,请让我知道我做错了什么。

提前致谢。

你可以维持selectedValue一个状态,然后使用。

带挂钩:

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

const UseHooksAndSelect = () => {
  const [dataPhase, setDataPhase] = useState([
    { phaseID: 1, phaseText: "Item 1" },
    { phaseID: 2, phaseText: "Item 2" },
    { phaseID: 3, phaseText: "Item 3" },
    { phaseID: 4, phaseText: "Item 4" },
    { phaseID: 5, phaseText: "Item 5" }
  ]);

  const [selOption, setSelOption] = useState({});

  const HandelChange = (obj) => {
    setSelOption(obj);
    console.log(obj);
  };

  console.log("Selected::", selOption.phaseID, selOption.phaseText);

  return (
    <Select
      isSearchable
      options={dataPhase}
      getOptionLabel={(option) => option.phaseText}
      getOptionValue={(option) => option.phaseText}
      className="diMultiSelect"
      classNamePrefix="diSelect"
      //  styles={styles}
      maxMenuHeight={150}
      value={selOption} // this doesn't let me click options
      onChange={(option) => HandelChange(option)} // this returns (option) => option.phaseText) as a string
    />
  );
};

export default UseHooksAndSelect;

和Class

在这里做实验:

import React, { Component } from "react";
import Select from "react-select";
import axios from "axios";

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedValue: {},
      selectOptions: [],
      id: "",
      name: ""
    };
  }

  async getOptions() {
    const res = await axios.get("https://jsonplaceholder.typicode.com/users");
    const data = res.data;

    const options = data.map((d) => ({
      value: d.id,
      label: d.name
    }));

    this.setState({ selectOptions: options });
  }

  handleChange(e) {
    console.log(e);
    this.setState({ selectedValue: e });
  }

  componentDidMount() {
    this.getOptions();
  }

  buttonClick = () => {
    const valueToSet = this.state.selectOptions.find((row) => {
      return row.value === 2 && row.label === "Ervin Howell";
    });

    if (valueToSet) {
      this.handleChange(valueToSet);
    }
  };

  render() {
    const { selectedValue = {} } = this.state;
    console.log(this.state.selectOptions);
    return (
      <div>
        <Select
          minMenuHeight={50}
          maxMenuHeight={100}
          value={selectedValue}
          options={this.state.selectOptions}
          onChange={this.handleChange.bind(this)}
        />
        <p>
          You have selected <strong>{selectedValue.label}</strong> whose id is{" "}
          <strong>{selectedValue.value}</strong>
        </p>
        <button onClick={this.buttonClick}>Click</button>
      </div>
    );
  }
}