在 react-select 中正确使用 NoOptionsMessage 来更改“无选项”文本

lai*_*man 5 reactjs react-select

我正在尝试更改react-select? 我能够使用以下代码做到这一点

<AsyncSelect 
    styles={customStyles} 
    components={{ DropdownIndicator: () => null, IndicatorSeparator: () => null, NoOptionsMessage: () => "test" }} 
    className="form-control firm-search"
    cacheOptions
    defaultOptions
    value={selectedValue}
    getOptionLabel={e => e.name}
    getOptionValue={e => e.path}
    loadOptions={loadOptions}
    onInputChange={handleInputChange}
    onChange={handleChange}
    placeholder='test ...'
/>
Run Code Online (Sandbox Code Playgroud)

问题是文本不再样式化。是否可以更改文本但保留默认样式?如果没有,是否可以将 CSS 应用于新文本?

Mur*_*ati 14

有两种方法可以设置自定义组件的样式。您可以将样式对象传递给styles支持或创建新的自定义组件。

以下代码显示了这两种方法。

import React from "react";
import "./style.css";
import Select, { components } from "react-select";

const msgStyles = {
  background: "skyblue",
  color: "white"
};

const NoOptionsMessage = props => {
  return (
    <components.NoOptionsMessage {...props}>
      <span className="custom-css-class">Text</span> 
    </components.NoOptionsMessage>
  );
};

const CustomNoOptionsMessage = () => {
  return (
    <Select
      isClearable
      components={{ NoOptionsMessage }}
      styles={{ noOptionsMessage: base => ({ ...base, ...msgStyles }) }}
      isSearchable
      name="color"
      options={[]}
    />
  );
};

export default function App() {
  return (
    <div>
      <CustomNoOptionsMessage />
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

在这里您可以找到工作代码:https://stackblitz.com/edit/react-lejn8c ?file=src/App.js


Vim*_*din 12

另一种方法可以做到这一点:

<AsyncSelect
  isClearable
  defaultOptions
  cacheOptions
  defaultOptions
  value={selectedValue}
  getOptionLabel={e => e.name}
  getOptionValue={e => e.path}
  loadOptions={loadOptions}
  onInputChange={handleInputChange}
  onChange={handleChange}
  noOptionsMessage={({inputValue}) => !inputValue ? noOptionsText : "No results found"} 
/>
Run Code Online (Sandbox Code Playgroud)