使用逗号在#react-select上创建新标签

问题描述 投票:0回答:2

在版本 1.3.0 每次用户按下“,”键时,react-select 都会创建一个新标签,这很有用,因为在实现此库之前,我们有这样的情况:用户将标签作为单个字符串而不是通过按输入。

不幸的是,在2.0重构后我找不到任何方法来做到这一点有什么方法可以配置此行为吗?

  • Example on version 1.3.0
  • Example on lastest version
javascript reactjs react-select
2个回答
2
投票

您需要进行一些自定义

react-select
才能实现您想要的。

基本上这就是我最终的结果:

import React, { Component } from "react";

import CreatableSelect from "react-select/lib/Creatable";

type State = {
  options: [{ [string]: string }],
  value: string | void
};

const createOption = (label: string) => ({
  label,
  value: label.toLowerCase().replace(/\W/g, "")
});

const defaultOptions = [
  createOption("One"),
  createOption("Two"),
  createOption("Three")
];

export default class CreatableAdvanced extends Component<*, State> {
  state = {
    inputValue: "",
    options: defaultOptions,
    value: []
  };
  onKeyDown = e => {
    if (e.keyCode === 188) {
      e.preventDefault();
      if (this.state.inputValue !== "") {
        this.handleCreate(this.selectRef.state.inputValue.slice(0, -1));
      }
    } else {
      this.setState({ inputValue: this.state.inputValue + e.key });
    }
  };
  handleChange = (newValue: any, actionMeta: any) => {
    this.setState({ value: newValue });
  };
  handleCreate = (inputValue: any) => {
    const { options, value } = this.state;
    const newOption = createOption(inputValue);
    this.setState({
      inputValue: "",
      options: [...options, newOption],
      value: [...value, newOption]
    });
  };
  render() {
    const { isLoading, options, value } = this.state;
    return (
      <CreatableSelect
        ref={r => (this.selectRef = r)}
        isClearable
        isMulti
        isDisabled={isLoading}
        isLoading={isLoading}
        inputValue={this.state.inputValue}
        onKeyDown={this.onKeyDown}
        onChange={this.handleChange}
        onCreateOption={this.handleCreate}
        options={options}
        value={value}
      />
    );
  }
}

这里是您想要的生动示例

这个想法是绕过 select 的原生

inputValue
并传递你自己的。使用
onKeyDown
功能,您可以决定填充
inputValue
或创建新标签。


0
投票

如果您使用

isMulti
,您可以使用逗号触发新值,就像使用
onInputChange
属性一样:

isMulti
onInputChange={(value, { action }) => {
  if (action === 'input-change') {
    const lastChar = value[value.length - 1]
    if (lastChar === ',') {
      const valueToAdd = value.slice(0, -1)
      // call your own state handler here
      onChange([...current, valueToAdd])

      // return the new text for the input
      return ''
    }
  }
}}
© www.soinside.com 2019 - 2024. All rights reserved.