如何通过另一个输入更新 React-Select 状态/选定值?

How to update React-Select state/ selected value via another input?

我正在学习 React 并尝试通过按钮更新 React-select 下拉菜单的 state/selected 值。单击按钮时,将调用 buttonClick() 函数来设置新的状态值,但 react-select 状态没有改变。下拉列表中的选定标签保持不变。如何更改 react-select 的状态以使其显示新的 selected 值?谢谢

https://codesandbox.io/s/react-select-test-nv8d8

实际上 handleChanges e 参数是所选选项的事件,而不是您要在 buttonClicks 事件中发送的对象:

  handleChange(e) {//e is the event not the object!
    console.log(e);
    this.setState({ id: e.value, name: e.label });
  }

  buttonClick = () => {        
    this.handleChange({ value: 2, label: "Ervin Howell" });// you can't pass object as the parameter
  };

对于按钮上的选定值,您可以这样做:

<Select
      value={{ id: this.state.id, label: this.state.name }}
      options={this.state.selectOptions}
      onChange={this.handleChange.bind(this)}
    />

react-select 期望 selection value 对象是作为 options

传递的选项之一

因此您需要跟踪状态中的 selected 值并将其传递给组件

同时检查按钮点击中的逻辑以获取选项并进行设置。

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: []
    };
  }

  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
          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>
    );
  }
}