如果在 React-Select v2 中搜索时没有剩余选项,我该如何创建新选项?

How do I create new option if there are no left while searching in React-Select v2?

如果没有剩余选项,我需要在过滤时创建带有标签 "Ostatni" 的新选项。我试图通过自定义 MenuListNoOptionsMessage 来做到这一点,但没有任何效果。有什么办法吗?

NoOptionsMessage = props => (
    <components.NoOptionsMessage
        {...props}
        children={<components.Option {...components.Option.defaultProps} data={{ value: 37, label: 'Ostatni' }} />}
    />
)

您可以使用 filterOption 函数实现您的目标,如下代码:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      hasExtraValue: false,
      options: [
        { label: "Label 1", value: 1 },
        { label: "Label 2", value: 2 },
        { label: "Label 3", value: 3 },
        { label: "Label 4", value: 4 },
        { label: "Label 5", value: 5 },
        { label: "Label 6", value: 6 },
        { label: "Label 7", value: 7 },
        { label: "Label 8", value: 8 },
        {label: 'Ostatni', value: 'other'}
      ]
    };
  }
  filterOption = (option, inputValue) => {
    // tweak the filterOption to render Ostatni only if there's no other option matching + set hasExtraValue to true in case you want to display an message
    if (option.label === "Ostatni"){
      const {options} = this.state
      const result = options.filter(opt => opt.label.includes(inputValue))
      this.setState({ hasExtraValue: !result.length})
       return !result.length
       };

    return option.label.includes(inputValue);
  };

  render() {
    return (
      <div>
        <Select
          isMulti
          filterOption={this.filterOption}
          noOptionsMessage={() => "No more options"}
          options={this.state.options}
        />
        // Displays a user friendly message to explain the situation
        {this.state.hasExtraValue && <p>Please select 'Ostatni' option if you don't find your option !</p>}
        </div>
    );
  }
}

这个想法是在用户输入内容时触发。如果没有可用选项,您可以添加一个新的所需标签以为用户提供新选项。

filterOption 中,您将此特殊选项设置为始终 true,因此如果它存在,它将始终显示。

Here a live example.

现在这似乎可以通过内置组件实现。

https://react-select.com/creatable

import React, { Component } from 'react';

import CreatableSelect from 'react-select/creatable';
import { colourOptions } from '../data';

export default class CreatableSingle extends Component<*, State> {
  handleChange = (newValue: any, actionMeta: any) => {
    console.group('Value Changed');
    console.log(newValue);
    console.log(`action: ${actionMeta.action}`);
    console.groupEnd();
  };
  handleInputChange = (inputValue: any, actionMeta: any) => {
    console.group('Input Changed');
    console.log(inputValue);
    console.log(`action: ${actionMeta.action}`);
    console.groupEnd();
  };
  render() {
    return (
      <CreatableSelect
        isClearable
        onChange={this.handleChange}
        onInputChange={this.handleInputChange}
        options={colourOptions}
      />
    );
  }
}