为反应渲染处理 .map 和 if/else 语句 - 使用 React-select [英] Handling .map and if/else statement for react render - using React-select

查看:28
本文介绍了为反应渲染处理 .map 和 if/else 语句 - 使用 React-select的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 react-select 和 creatable 函数,它允许您创建一个新的选择选项 - 只需在示例中输入选择/输入字段.当您输入第一个自定义选项时,它默认为一个名为新组"的组.当您创建第二个自定义选项时,这应该覆盖新组中的第一个.但是组名消失了.

I am using react-select and the creatable function that allows you to create a new select option - just type in the select/input field on example. When you type in the first custom option it defaults into a group called "new Group". When you create a 2nd custom option this should overwrite the first in the new group. However the group name disappears.

这是导致该行为的错误代码...

This is the incorrect code that results in that behavior...

  if (this.state.hasCreatedOption) {
    options[this.state.hasCreatedOption] = newOption;
  } else {
    options.map(option => {
      if (option.label === "New group") {
        return {
          label: option.label,
          options: option.options.push(newOption)
        };
      }
      return option;
    });
  }

  hasCreatedOption = options.length - 1;

这是创建的示例 - https://codesandbox.io/s/w761j8v855>

Here is the example created - https://codesandbox.io/s/w761j8v855

推荐答案

在你的情况下,你知道你的自定义选项组位于你的选项数组的最后,我什至会减少代码并提高速度/性能其代码如下:

As in your case you know that your custom option group is at the very end of your options array, I would even right less code and improve the speed / performance of it with the following code:

state = {
    value: this.props.options[0].options,
    options: this.props.options,
    hasCreatedOption: this.props.options.length - 1
  };
  handleCreate = input => (inputValue: any) => {
    this.setState({ isLoading: true });

    setTimeout(() => {
      const { options } = this.state;
      const newOption = createOption(inputValue);
      options[this.state.hasCreatedOption].options[0] = newOption;

      this.setState({
        isLoading: false,
        options: [...options],
        value: newOption,
        formatGroupLabel: "new label"
      });
      input.onChange(newOption);
    }, 1000);
  };

当您声明自定义选项组时,您基本上知道它的索引,并且可以直接更新正确的数组,而无需遍历您可能拥有的所有不同组.这里是示例.

As you declare your custom option group you basically know the index of it and can directly update the right array without looping through all of the different group you may have. Here the example.

这篇关于为反应渲染处理 .map 和 if/else 语句 - 使用 React-select的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆