使用setState(react-select)将具有可变键的多个对象推入数组

时间:2019-02-06 13:13:45

标签: reactjs ecmascript-6 react-select

我的目标是使用来自端点的数据创建反应选择选择,该端点具有类别的查询变量(在此示例中为风味)。因此,我想动态创建这些选择输入,并设置了一个组件来包装主要的反应选择代码,因此我只需要一个处理函数。

这是我的主文件

const flavours1 = [
  { value: "chocolate", label: "Chocolate" },
  { value: "strawberry", label: "Strawberry" }
];
const flavours2 = [
  { value: "banana", label: "Banana" },
  { value: "kiwi", label: "Kiwi" }
];

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      test: "test",
      selectedOptions: null
    };
  }

  // Here I want to setState but with the name of each SelectComponent as the key for each object and also push to the existing array rather than over writing it as is currently
  addSelectedOption = (...args) => {
    this.setState({
      selectedOptions: [args[0]]
    });
  };

  componentDidUpdate() {
    console.log(this.state);
  }

  render() {
    return (
      <div style={styles}>
        <SelectComponent
          name="flavours1"
          options={flavours1}
          addSelectedOption={this.addSelectedOption}
        />
        <SelectComponent
          name="flavours2"
          options={flavours2}
          addSelectedOption={this.addSelectedOption}
        />
      </div>
    );
  }
}

以及组件:

    import Select from "react-select";

    export default class SelectComponent extends Component {
      constructor(props) {
        super(props);

        this.state = {
          selectedOptions: null
        };
      }

      render() {
        return (
          <form>
            <Select
              isMulti
              onChange={this.props.addSelectedOption}
              value={this && this.state ? this.state.option : null}
              options={this.props.options}
              ref={input => {
                this.selectField = input;
              }}
            />
          </form>
        );
      }
    }

到目前为止,这是我的示例:https://codesandbox.io/s/llzw409n3z

所以我正在努力的两件事是:

  • 将对象推送为数组,保留所有选定的对象 值(当前在每个不同的选择上进行选择会覆盖 其他
  • 根据SelectComponent的名称属性为每个对象分配一个键

目标是获得结构

selectedOptions: [
  flavours1: [
    { value: "chocolate", label: "Chocolate" },
    { value: "strawberry", label: "Strawberry" }
  ],
  flavours2: [
    { value: "banana", label: "Banana" },
    { value: "kiwi", label: "Kiwi" }
  ],
];

1 个答案:

答案 0 :(得分:1)

当前react-select组件未提供触发change事件的组件的名称。因此,您需要通过使SelectComponent在内部处理onChange事件,然后将this.props.name传递给addSelectedOption处理程序来添加它。

添加

  handleChange = (...args) => {
    this.props.addSelectedOption(this.props.name, ...args)
  }

并应用

    <Select
      onChange={this.handleChange}
      ...
     />

现在您可以在添加组件上使用

  addSelectedOption = (name, options) => {
    this.setState(({selectedOptions})=>({
      selectedOptions: {
        ...selectedOptions,
        [name]: options
        }
    }))
  };

但是您必须像这样初始化state

this.state = {
  test: "test",
  selectedOptions: {}
};

以便您在使用selectedOptions时可以传播setState

Edit Multiple dynamic react-select