@128technology/react-select 中文文档教程

发布于 5年前 浏览 20 项目主页 更新于 3年前

 NPMCDNJS构建状态覆盖状态Supported by Thinkmill

React-Select

使用 React 构建的 Select 控件。 最初构建用于 KeystoneJS

Demo & Examples

现场演示:jedwatson.github.io/react-select

Installation

使用 react-select 最简单的方法是从以下位置安装它npm 并使用 Webpack 将其构建到您的应用程序中。

yarn add react-select

然后,您可以在应用程序中导入 react-select 及其样式,如下所示:

import Select from 'react-select';
import 'react-select/dist/react-select.css';

您还可以通过包含 dist/react-select.jsdist/react-select 来使用独立的 UMD 构建。 css 在你的页面中。 如果这样做,您还需要包含依赖项。 例如:

<script src="https://unpkg.com/react@15.6.1/dist/react.js"></script>
<script src="https://unpkg.com/react-dom@15.6.1/dist/react-dom.js"></script>
<script src="https://unpkg.com/prop-types@15.5.10/prop-types.js"></script>
<script src="https://unpkg.com/classnames@2.2.5/index.js"></script>
<script src="https://unpkg.com/react-input-autosize@2.0.0/dist/react-input-autosize.js"></script>
<script src="https://unpkg.com/react-select/dist/react-select.js"></script>

<link rel="stylesheet" href="https://unpkg.com/react-select/dist/react-select.css">

Usage

React-Select 生成一个包含所选值的隐藏文本字段,因此您可以将其作为标准表单的一部分提交。 您还可以使用 onChange 事件属性监听更改。

选项应作为 ObjectArray 提供,每个选项都具有用于呈现和搜索的 valuelabel 属性. 您可以使用 disabled 属性来指示该选项是否被禁用。

每个选项的 value 属性应该是字符串或数字。

当值更改时,onChange(selectedValueOrValues) 将触发。 请注意(从 1.0 开始)您必须处理更改并将更新后的传递给 Select。

import React from 'react';
import Select from 'react-select';

class App extends React.Component {
  state = {
    selectedOption: '',
  }
  handleChange = (selectedOption) => {
    this.setState({ selectedOption });
    console.log(`Selected: ${selectedOption.label}`);
  }
  render() {
      const { selectedOption } = this.state;
      const value = selectedOption && selectedOption.value;

    return (
      <Select
        name="form-field-name"
        value={value}
        onChange={this.handleChange}
        options={[
          { value: 'one', label: 'One' },
          { value: 'two', label: 'Two' },
        ]}
      />
    );
  }
}

您可以自定义 valueKeylabelKey 道具以使用不同的选项形状。

Custom classNames

您可以为

内置选项渲染器还支持自定义类名,只需将 className 属性添加到 options 数组中的对象即可。

Multiselect options

您可以通过设置 multi={true} 启用多值选择。 在这种模式下:

  • Selected options will be removed from the dropdown menu by default. If you want them to remain in the list, set removeSelected={false}
  • The selected values are submitted in multiple <input type="hidden"> fields, use the joinValues prop to submit joined values in a single field instead
  • The values of the selected items are joined using the delimiter prop to create the input value when joinValues is true
  • A simple value, if provided, will be split using the delimiter prop
  • The onChange event provides an array of selected options or a comma-separated string of values (eg "1,2,3") if simpleValue is true
  • By default, only options in the options array can be selected. Use the Creatable Component (which wraps Select) to allow new options to be created if they do not already exist. Hitting comma (','), ENTER or TAB will add a new option. Versions 0.9.x and below provided a boolean attribute on the Select Component (allowCreate) to achieve the same functionality. It is no longer available starting with version 1.0.0.
  • By default, selected options can be cleared. To disable the possibility of clearing a particular option, add clearableValue: false to that option:
var options = [
  { value: 'one', label: 'One' },
  { value: 'two', label: 'Two', clearableValue: false }
];

注意:Select 组件的 clearable 属性也应该设置为 false 以防止允许一次清除所有字段

Accessibility Note

Selected values are not focus targets, 这意味着键盘用户不能切换到它们,并且只能按顺序使用退格键删除它们。 这并不理想,我正在寻找未来的其他选择; 同时,如果您想使用实现 tabIndex 和键盘事件处理的自定义 valueComponent,请参见#2098 示例。

Async options

如果您想异步加载选项,请使用 Async 导出并提供 loadOptions 函数。

该函数有两个参数 String input, Function callback,当输入文本改变时将被调用。

当您的异步进程完成获取选项时,将它们传递给对象 { options: [] } 中的 callback(err, data)

选择控件将智能地缓存已获取的输入字符串的选项。 缓存的结果集将在输入更具体的搜索时进行过滤,因此如果您的异步过程只会为更具体的查询返回较小的结果集,还可以在回调对象中传递 complete: true。 可以通过将 cache 设置为 false 来禁用缓存(请注意 complete: true 将无效)。

除非您指定 autoload={false} 属性,否则控件将在安装时自动加载默认选项集(即 input: '')。

import { Async } from 'react-select';

const getOptions = (input, callback) => {
  setTimeout(() => {
    callback(null, {
      options: [
        { value: 'one', label: 'One' },
        { value: 'two', label: 'Two' }
      ],
      // CAREFUL! Only set this to true when there are no more options,
      // or more specific queries will not be sent to the server.
      complete: true
    });
  }, 500);
};

<Async
    name="form-field-name"
    loadOptions={getOptions}
/>

Note about filtering async options

Async 组件不会更改根据用户输入过滤选项的默认行为,但如果您已经在服务器端过滤选项,您可能需要自定义或禁用此功能(请参阅 < a href="#filtering-options">过滤选项如下)。 例如,如果您想完全禁用客户端过滤,您可以这样做:

filterOptions={(options, filter, currentValues) => {
  // Do no filtering, just return all options
  return options;
}}

Async options with Promises

loadOptions 支持 Promises,它的使用方式与回调非常相似。

适用于带回调的 loadOptions 的所有内容仍然适用于 Promises 方法(例如缓存、自动加载等)

。使用 fetch API 和 ES6 语法的示例,以及返回一个对象,如:

import { Async } from 'react-select';

/*
 * assuming the API returns something like this:
 *   const json = [
 *      { value: 'one', label: 'One' },
 *      { value: 'two', label: 'Two' }
 *   ]
 */

const getOptions = (input) => {
  return fetch(`/users/${input}.json`)
    .then((response) => {
      return response.json();
    }).then((json) => {
      return { options: json };
    });
}

<Async
  name="form-field-name"
  value="one"
  loadOptions={getOptions}
/>

Async options loaded externally

如果您想从 Select 组件异步加载选项,您可以通过传入 isLoading< 让 Select 组件显示加载微调器/code> 属性设置为 true

import Select from 'react-select';

let isLoadingExternally = true;

<Select
  name="form-field-name"
  isLoading={isLoadingExternally}
  ...
/>

User-created tags

Creatable 组件使用户能够在 react-select 中创建新标签。 它装饰了一个Select,因此除了几个自定义属性(如下所示)之外,它还支持所有默认属性(例如单/多模式、过滤等)。 最简单的使用方法如下:

import { Creatable } from 'react-select';

function render (selectProps) {
  return <Creatable {...selectProps} />;
};

Combining Async and Creatable

如果您同时需要asynccreatable 功能,请使用AsyncCreatable HOC。 它将 AsyncCreatable 组件联系在一起,并支持它们的属性(如上所列)的联合。 按如下方式使用它:

import { AsyncCreatable } from 'react-select';

function render (props) {
  // props can be a mix of Async, Creatable, and Select properties
  return (
    <AsyncCreatable {...props} />
  );
}

Filtering options

您可以使用以下属性控制选项的过滤方式:

  • matchPos: "start" or "any": whether to match the text entered at the start or any position in the option value
  • matchProp: "label", "value" or "any": whether to match the value, label or both values of each option when filtering
  • ignoreCase: Boolean: whether to ignore case or match the text exactly when filtering
  • ignoreAccents: Boolean: whether to ignore accents on characters like ø or å

matchPropmatchPos 均默认为 "any"ignoreCase 默认为 trueignoreAccents 默认为 true

Advanced filters

您还可以完全替换用于过滤单个选项或整个选项数组(允许自定义排序机制等)的方法

  • filterOption: function(Object option, String filter) returns Boolean. Will override matchPos, matchProp, ignoreCase and ignoreAccents options.
  • filterOptions: function(Array options, String filter, Array currentValues) returns Array filteredOptions. Will override filterOption, matchPos, matchProp, ignoreCase and ignoreAccents options.

。对于多选输入,在提供自定义 filterOptions 方法时,请记住从返回的选项数组中排除当前值。

Filtering large lists

每次过滤器文本更改时,默认的 filterOptions 方法都会扫描选项数组以查找匹配项。 这很好用,但随着选项数组增长到数百个对象,速度可能会变慢。 对于更大的选项列表,自定义过滤器函数如 react-select-fast-filter-options 会产生更好的结果。

Efficiently rendering large lists with windowing

menuRenderer 属性可用于覆盖默认的选项下拉列表。 这应该在列表很大(成百上千个项目)时完成,以便更快地呈现。 然后可以使用像 react-virtualized 这样的窗口库来更有效地呈现下拉菜单像这样。 最简单的方法是使用 react-virtualized-select HOC。 该组件装饰了一个 Select 并使用反应虚拟化的 VirtualScroll 组件来呈现选项。 此组件的演示和文档可在此处获得。

您还可以指定自己的自定义渲染器。 自定义 menuRenderer 属性接受以下命名参数:

ParameterTypeDescription
focusedOptionObjectThe currently focused option; should be visible in the menu by default.
focusOptionFunctionCallback to focus a new option; receives the option as a parameter.
labelKeyStringOption labels are accessible with this string key.
optionClassNameStringThe className that gets used for options
optionComponentReactClassThe react component that gets used for rendering an option
optionRendererFunctionThe function that gets used to render the content of an option
optionsArray<Object>Ordered array of options to render.
selectValueFunctionCallback to select a new option; receives the option as a parameter.
valueArrayArray<Object>Array of currently selected options.

Updating input values with onInputChange

您可以通过提供返回新值的 onInputChange 回调来操纵输入。 请注意:当您只想使用onInputChange 来监听输入更新时,您仍然必须返回未更改的值!

function cleanInput(inputValue) {
    // Strip all non-number characters from the input
    return inputValue.replace(/[^0-9]/g, "");
}   

<Select
    name="form-field-name"
    onInputChange={cleanInput}
/>

Overriding default key-down behaviour with onInputKeyDown

Select 监听 keyDown 事件来选择项目,通过箭头键导航下拉列表等。 您可以通过提供 onInputKeyDown 回调来扩展或覆盖此行为。

function onInputKeyDown(event) {
    switch (event.keyCode) {
        case 9:   // TAB
            // Extend default TAB behaviour by doing something here
            break;
        case 13: // ENTER
            // Override default ENTER behaviour by doing stuff here and then preventing default
            event.preventDefault();
            break;
    }
}

<Select
    {...otherProps}
    onInputKeyDown={onInputKeyDown}
/>

Select Props

PropertyTypeDefaultDescription
aria-describedbystringundefinedHTML ID(s) of element(s) that should be used to describe this input (for assistive tech)
aria-labelstringundefinedAria label (for assistive tech)
aria-labelledbystringundefinedHTML ID of an element that should be used as the label (for assistive tech)
arrowRendererfunctionundefinedRenders a custom drop-down arrow to be shown in the right-hand side of the select: arrowRenderer({ onMouseDown, isOpen }). Won't render when set to null
autoBlurbooleanfalseBlurs the input element after a selection has been made. Handy for lowering the keyboard on mobile devices
autofocusbooleanundefineddeprecated; use the autoFocus prop instead
autoFocusbooleanundefinedautofocus the component on mount
autoloadbooleantruewhether to auto-load the default async options set
autosizebooleantrueIf enabled, the input will expand as the length of its value increases
backspaceRemovesbooleantruewhether pressing backspace removes the last item when there is no input value
backspaceToRemoveMessagestring'Press backspace to remove {last label}'prompt shown in input when at least one option in a multiselect is shown, set to '' to clear
classNamestringundefinedclassName for the outer element
clearablebooleantrueshould it be possible to reset value
clearAllTextstring'Clear all'title for the "clear" control when multi is true
clearRendererfunctionundefinedRenders a custom clear to be shown in the right-hand side of the select when clearable true: clearRenderer()
clearValueTextstring'Clear value'title for the "clear" control
closeOnSelectbooleantruewhether to close the menu when a value is selected
deleteRemovesbooleantruewhether pressing delete key removes the last item when there is no input value
delimiterstring','delimiter to use to join multiple values
disabledbooleanfalsewhether the Select is disabled or not
escapeClearsValuebooleantruewhether escape clears the value when the menu is closed
filterOptionfunctionundefinedmethod to filter a single option (option, filterString) => boolean
filterOptionsboolean or functionundefinedboolean to enable default filtering or function to filter the options array ([options], filterString, [values]) => [options]
idstringundefinedhtml id to set on the input element for accessibility or tests
ignoreAccentsbooleantruewhether to strip accents when filtering
ignoreCasebooleantruewhether to perform case-insensitive filtering
inputPropsobjectundefinedcustom attributes for the Input (in the Select-control) e.g: {'data-foo': 'bar'}
inputRendererfunctionundefinedrenders a custom input component
instanceIdstringincrementinstance ID used internally to set html ids on elements for accessibility, specify for universal rendering
isLoadingbooleanfalsewhether the Select is loading externally or not (such as options being loaded)
joinValuesbooleanfalsejoin multiple values into a single hidden input using the delimiter
labelKeystring'label'the option property to use for the label
matchPosstring'any'(any, start) match the start or entire string when filtering
matchPropstring'any'(any, label, value) which option property to filter on
menuBuffernumber0buffer of px between the base of the dropdown and the viewport to shift if menu doesnt fit in viewport
menuContainerStyleobjectundefinedoptional style to apply to the menu container
menuRendererfunctionundefinedRenders a custom menu with options; accepts the following named parameters: menuRenderer({ focusedOption, focusOption, options, selectValue, valueArray })
menuStyleobjectundefinedoptional style to apply to the menu
multibooleanundefinedmulti-value input
namestringundefinedfield name, for hidden <input /> tag
noResultsTextstring'No results found'placeholder displayed when there are no matching search results or a falsy value to hide it (can also be a react component)
onBlurfunctionundefinedonBlur handler: function(event) {}
onBlurResetsInputbooleantrueWhether to clear input on blur or not. If set to false, it only works if onCloseResetsInput is false as well.
onChangefunctionundefinedonChange handler: function(newOption) {}
onClosefunctionundefinedhandler for when the menu closes: function () {}
onCloseResetsInputbooleantruewhether to clear input when closing the menu through the arrow
onFocusfunctionundefinedonFocus handler: function(event) {}
onInputChangefunctionundefinedonInputChange handler/interceptor: function(inputValue: string): string
onInputKeyDownfunctionundefinedinput keyDown handler; call event.preventDefault() to override default Select behaviour: function(event) {}
onMenuScrollToBottomfunctionundefinedcalled when the menu is scrolled to the bottom
onOpenfunctionundefinedhandler for when the menu opens: function () {}
onSelectResetsInputbooleantruewhether the input value should be reset when options are selected. Also input value will be set to empty if 'onSelectResetsInput=true' and Select will get new value that not equal previous value.
onValueClickfunctionundefinedonClick handler for value labels: function (value, event) {}
openOnClickbooleantrueopen the options menu when the control is clicked (requires searchable = true)
openOnFocusbooleanfalseopen the options menu when the control gets focus
optionClassName: stringundefinedadditional class(es) to apply to the
optionComponentfunctionundefinedoption component to render in dropdown
optionRendererfunctionundefinedcustom function to render the options in the menu
optionsarrayundefinedarray of options
removeSelectedbooleantruewhether the selected option is removed from the dropdown on multi selects
pageSizenumber5number of options to jump when using page up/down keys
placeholderstring or node'Select …'field placeholder, displayed when there's no value
requiredbooleanfalseapplies HTML5 required attribute when needed
resetValueanynullvalue to set when the control is cleared
rtlbooleanfalseuse react-select in right-to-left direction
scrollMenuIntoViewbooleantruewhether the viewport will shift to display the entire menu when engaged
searchablebooleantruewhether to enable searching feature or not
searchPromptTextstring or node'Type to search'label to prompt for search input
simpleValuebooleanfalsepass the value to onChange as a string
styleobjectundefinedoptional styles to apply to the control
tabIndexstring or numberundefinedtabIndex of the control
tabSelectsValuebooleantruewhether to select the currently focused value when the [tab] key is pressed
trimFilterbooleanfalsewhether to trim whitespace from the filter value
valueanyundefinedinitial field value
valueComponentfunctionfunction which returns a custom way to render/manage the value selected <CustomValue />
valueKeystring'value'the option property to use for the value
valueRendererfunctionundefinedfunction which returns a custom way to render the value selected function (option) {}
wrapperStyleobjectundefinedoptional styles to apply to the component wrapper

Async Props

PropertyTypeDefaultDescription
autoloadbooleantrueautomatically call the loadOptions prop on-mount
cacheobjectundefinedSets the cache object used for options. Set to false if you would like to disable caching.
loadingPlaceholderstring or node'Loading…'label to prompt for loading search result
loadOptionsfunctionundefinedfunction that returns a promise or calls a callback with the options: function(input, [callback])

Creatable properties

PropertyTypeDescription
childrenfunctionChild function responsible for creating the inner Select component. This component can be used to compose HOCs (eg Creatable and Async). Expected signature: (props: Object): PropTypes.element
isOptionUniquefunctionSearches for any matching option within the set of options. This function prevents duplicate options from being created. By default this is a basic, case-sensitive comparison of label and value. Expected signature: ({ option: Object, options: Array, labelKey: string, valueKey: string }): boolean
isValidNewOptionfunctionDetermines if the current input text represents a valid option. By default any non-empty string will be considered valid. Expected signature: ({ label: string }): boolean
newOptionCreatorfunctionFactory to create new option. Expected signature: ({ label: string, labelKey: string, valueKey: string }): Object
onNewOptionClickfunctionnew option click handler, it calls when new option has been selected. function(option) {}
shouldKeyDownEventCreateNewOptionfunctionDecides if a keyDown event (eg its keyCode) should result in the creation of a new option. ENTER, TAB and comma keys create new options by default. Expected signature: ({ keyCode: number }): boolean
promptTextCreatorfunctionFactory for overriding default option creator prompt label. By default it will read 'Create option "{label}"'. Expected signature: (label: String): String

Methods

使用 focus() 方法为控件提供焦点。

// focuses the input element
<instance>.focus();

Contributing

有关如何贡献的信息,请参阅我们的 CONTRIBUTING.md

感谢以下项目的启发:Selectize(在行为和用户体验方面),React-Autocomplete(作为高质量的 React Combobox 实现),以及其他选择控件,包括 选择选择2

License

麻省理工学院许可。 版权所有 (c) Jed Watson 2018。

NPMCDNJSBuild StatusCoverage StatusSupported by Thinkmill

React-Select

A Select control built with and for React. Initially built for use in KeystoneJS.

Demo & Examples

Live demo: jedwatson.github.io/react-select

Installation

The easiest way to use react-select is to install it from npm and build it into your app with Webpack.

yarn add react-select

You can then import react-select and its styles in your application as follows:

import Select from 'react-select';
import 'react-select/dist/react-select.css';

You can also use the standalone UMD build by including dist/react-select.js and dist/react-select.css in your page. If you do this you'll also need to include the dependencies. For example:

<script src="https://unpkg.com/react@15.6.1/dist/react.js"></script>
<script src="https://unpkg.com/react-dom@15.6.1/dist/react-dom.js"></script>
<script src="https://unpkg.com/prop-types@15.5.10/prop-types.js"></script>
<script src="https://unpkg.com/classnames@2.2.5/index.js"></script>
<script src="https://unpkg.com/react-input-autosize@2.0.0/dist/react-input-autosize.js"></script>
<script src="https://unpkg.com/react-select/dist/react-select.js"></script>

<link rel="stylesheet" href="https://unpkg.com/react-select/dist/react-select.css">

Usage

React-Select generates a hidden text field containing the selected value, so you can submit it as part of a standard form. You can also listen for changes with the onChange event property.

Options should be provided as an Array of Objects, each with a value and label property for rendering and searching. You can use a disabled property to indicate whether the option is disabled or not.

The value property of each option should be either a string or a number.

When the value is changed, onChange(selectedValueOrValues) will fire. Note that (as of 1.0) you must handle the change and pass the updated value to the Select.

import React from 'react';
import Select from 'react-select';

class App extends React.Component {
  state = {
    selectedOption: '',
  }
  handleChange = (selectedOption) => {
    this.setState({ selectedOption });
    console.log(`Selected: ${selectedOption.label}`);
  }
  render() {
      const { selectedOption } = this.state;
      const value = selectedOption && selectedOption.value;

    return (
      <Select
        name="form-field-name"
        value={value}
        onChange={this.handleChange}
        options={[
          { value: 'one', label: 'One' },
          { value: 'two', label: 'Two' },
        ]}
      />
    );
  }
}

You can customise the valueKey and labelKey props to use a different option shape.

Custom classNames

You can provide a custom className prop to the <Select> component, which will be added to the base .Select className for the outer container.

The built-in Options renderer also support custom classNames, just add a className property to objects in the options array.

Multiselect options

You can enable multi-value selection by setting multi={true}. In this mode:

  • Selected options will be removed from the dropdown menu by default. If you want them to remain in the list, set removeSelected={false}
  • The selected values are submitted in multiple <input type="hidden"> fields, use the joinValues prop to submit joined values in a single field instead
  • The values of the selected items are joined using the delimiter prop to create the input value when joinValues is true
  • A simple value, if provided, will be split using the delimiter prop
  • The onChange event provides an array of selected options or a comma-separated string of values (eg "1,2,3") if simpleValue is true
  • By default, only options in the options array can be selected. Use the Creatable Component (which wraps Select) to allow new options to be created if they do not already exist. Hitting comma (','), ENTER or TAB will add a new option. Versions 0.9.x and below provided a boolean attribute on the Select Component (allowCreate) to achieve the same functionality. It is no longer available starting with version 1.0.0.
  • By default, selected options can be cleared. To disable the possibility of clearing a particular option, add clearableValue: false to that option:
var options = [
  { value: 'one', label: 'One' },
  { value: 'two', label: 'Two', clearableValue: false }
];

Note: the clearable prop of the Select component should also be set to false to prevent allowing clearing all fields at once

Accessibility Note

Selected values aren't focus targets, which means keyboard users can't tab to them, and are restricted to removing them using backspace in order. This isn't ideal and I'm looking at other options for the future; in the meantime if you want to use a custom valueComponent that implements tabIndex and keyboard event handling, see #2098 for an example.

Async options

If you want to load options asynchronously, use the Async export and provide a loadOptions Function.

The function takes two arguments String input, Function callbackand will be called when the input text is changed.

When your async process finishes getting the options, pass them to callback(err, data) in a Object { options: [] }.

The select control will intelligently cache options for input strings that have already been fetched. The cached result set will be filtered as more specific searches are input, so if your async process would only return a smaller set of results for a more specific query, also pass complete: true in the callback object. Caching can be disabled by setting cache to false (Note that complete: true will then have no effect).

Unless you specify the property autoload={false} the control will automatically load the default set of options (i.e. for input: '') when it is mounted.

import { Async } from 'react-select';

const getOptions = (input, callback) => {
  setTimeout(() => {
    callback(null, {
      options: [
        { value: 'one', label: 'One' },
        { value: 'two', label: 'Two' }
      ],
      // CAREFUL! Only set this to true when there are no more options,
      // or more specific queries will not be sent to the server.
      complete: true
    });
  }, 500);
};

<Async
    name="form-field-name"
    loadOptions={getOptions}
/>

Note about filtering async options

The Async component doesn't change the default behaviour for filtering the options based on user input, but if you're already filtering the options server-side you may want to customise or disable this feature (see filtering options below). For example, if you would like to completely disable client side filtering, you can do so with:

filterOptions={(options, filter, currentValues) => {
  // Do no filtering, just return all options
  return options;
}}

Async options with Promises

loadOptions supports Promises, which can be used in very much the same way as callbacks.

Everything that applies to loadOptions with callbacks still applies to the Promises approach (e.g. caching, autoload, …)

An example using the fetch API and ES6 syntax, with an API that returns an object like:

import { Async } from 'react-select';

/*
 * assuming the API returns something like this:
 *   const json = [
 *      { value: 'one', label: 'One' },
 *      { value: 'two', label: 'Two' }
 *   ]
 */

const getOptions = (input) => {
  return fetch(`/users/${input}.json`)
    .then((response) => {
      return response.json();
    }).then((json) => {
      return { options: json };
    });
}

<Async
  name="form-field-name"
  value="one"
  loadOptions={getOptions}
/>

Async options loaded externally

If you want to load options asynchronously externally from the Select component, you can have the Select component show a loading spinner by passing in the isLoading prop set to true.

import Select from 'react-select';

let isLoadingExternally = true;

<Select
  name="form-field-name"
  isLoading={isLoadingExternally}
  ...
/>

User-created tags

The Creatable component enables users to create new tags within react-select. It decorates a Select and so it supports all of the default properties (eg single/multi mode, filtering, etc) in addition to a couple of custom ones (shown below). The easiest way to use it is like so:

import { Creatable } from 'react-select';

function render (selectProps) {
  return <Creatable {...selectProps} />;
};

Combining Async and Creatable

Use the AsyncCreatable HOC if you want both async and creatable functionality. It ties Async and Creatable components together and supports a union of their properties (listed above). Use it as follows:

import { AsyncCreatable } from 'react-select';

function render (props) {
  // props can be a mix of Async, Creatable, and Select properties
  return (
    <AsyncCreatable {...props} />
  );
}

Filtering options

You can control how options are filtered with the following props:

  • matchPos: "start" or "any": whether to match the text entered at the start or any position in the option value
  • matchProp: "label", "value" or "any": whether to match the value, label or both values of each option when filtering
  • ignoreCase: Boolean: whether to ignore case or match the text exactly when filtering
  • ignoreAccents: Boolean: whether to ignore accents on characters like ø or å

matchProp and matchPos both default to "any". ignoreCase defaults to true. ignoreAccents defaults to true.

Advanced filters

You can also completely replace the method used to filter either a single option, or the entire options array (allowing custom sort mechanisms, etc.)

  • filterOption: function(Object option, String filter) returns Boolean. Will override matchPos, matchProp, ignoreCase and ignoreAccents options.
  • filterOptions: function(Array options, String filter, Array currentValues) returns Array filteredOptions. Will override filterOption, matchPos, matchProp, ignoreCase and ignoreAccents options.

For multi-select inputs, when providing a custom filterOptions method, remember to exclude current values from the returned array of options.

Filtering large lists

The default filterOptions method scans the options array for matches each time the filter text changes. This works well but can get slow as the options array grows to several hundred objects. For larger options lists a custom filter function like react-select-fast-filter-options will produce better results.

Efficiently rendering large lists with windowing

The menuRenderer property can be used to override the default drop-down list of options. This should be done when the list is large (hundreds or thousands of items) for faster rendering. Windowing libraries like react-virtualized can then be used to more efficiently render the drop-down menu like so. The easiest way to do this is with the react-virtualized-select HOC. This component decorates a Select and uses the react-virtualized VirtualScroll component to render options. Demo and documentation for this component are available here.

You can also specify your own custom renderer. The custom menuRenderer property accepts the following named parameters:

ParameterTypeDescription
focusedOptionObjectThe currently focused option; should be visible in the menu by default.
focusOptionFunctionCallback to focus a new option; receives the option as a parameter.
labelKeyStringOption labels are accessible with this string key.
optionClassNameStringThe className that gets used for options
optionComponentReactClassThe react component that gets used for rendering an option
optionRendererFunctionThe function that gets used to render the content of an option
optionsArray<Object>Ordered array of options to render.
selectValueFunctionCallback to select a new option; receives the option as a parameter.
valueArrayArray<Object>Array of currently selected options.

Updating input values with onInputChange

You can manipulate the input by providing a onInputChange callback that returns a new value. Please note: When you want to use onInputChange only to listen to the input updates, you still have to return the unchanged value!

function cleanInput(inputValue) {
    // Strip all non-number characters from the input
    return inputValue.replace(/[^0-9]/g, "");
}   

<Select
    name="form-field-name"
    onInputChange={cleanInput}
/>

Overriding default key-down behaviour with onInputKeyDown

Select listens to keyDown events to select items, navigate drop-down list via arrow keys, etc. You can extend or override this behaviour by providing a onInputKeyDown callback.

function onInputKeyDown(event) {
    switch (event.keyCode) {
        case 9:   // TAB
            // Extend default TAB behaviour by doing something here
            break;
        case 13: // ENTER
            // Override default ENTER behaviour by doing stuff here and then preventing default
            event.preventDefault();
            break;
    }
}

<Select
    {...otherProps}
    onInputKeyDown={onInputKeyDown}
/>

Select Props

PropertyTypeDefaultDescription
aria-describedbystringundefinedHTML ID(s) of element(s) that should be used to describe this input (for assistive tech)
aria-labelstringundefinedAria label (for assistive tech)
aria-labelledbystringundefinedHTML ID of an element that should be used as the label (for assistive tech)
arrowRendererfunctionundefinedRenders a custom drop-down arrow to be shown in the right-hand side of the select: arrowRenderer({ onMouseDown, isOpen }). Won't render when set to null
autoBlurbooleanfalseBlurs the input element after a selection has been made. Handy for lowering the keyboard on mobile devices
autofocusbooleanundefineddeprecated; use the autoFocus prop instead
autoFocusbooleanundefinedautofocus the component on mount
autoloadbooleantruewhether to auto-load the default async options set
autosizebooleantrueIf enabled, the input will expand as the length of its value increases
backspaceRemovesbooleantruewhether pressing backspace removes the last item when there is no input value
backspaceToRemoveMessagestring'Press backspace to remove {last label}'prompt shown in input when at least one option in a multiselect is shown, set to '' to clear
classNamestringundefinedclassName for the outer element
clearablebooleantrueshould it be possible to reset value
clearAllTextstring'Clear all'title for the "clear" control when multi is true
clearRendererfunctionundefinedRenders a custom clear to be shown in the right-hand side of the select when clearable true: clearRenderer()
clearValueTextstring'Clear value'title for the "clear" control
closeOnSelectbooleantruewhether to close the menu when a value is selected
deleteRemovesbooleantruewhether pressing delete key removes the last item when there is no input value
delimiterstring','delimiter to use to join multiple values
disabledbooleanfalsewhether the Select is disabled or not
escapeClearsValuebooleantruewhether escape clears the value when the menu is closed
filterOptionfunctionundefinedmethod to filter a single option (option, filterString) => boolean
filterOptionsboolean or functionundefinedboolean to enable default filtering or function to filter the options array ([options], filterString, [values]) => [options]
idstringundefinedhtml id to set on the input element for accessibility or tests
ignoreAccentsbooleantruewhether to strip accents when filtering
ignoreCasebooleantruewhether to perform case-insensitive filtering
inputPropsobjectundefinedcustom attributes for the Input (in the Select-control) e.g: {'data-foo': 'bar'}
inputRendererfunctionundefinedrenders a custom input component
instanceIdstringincrementinstance ID used internally to set html ids on elements for accessibility, specify for universal rendering
isLoadingbooleanfalsewhether the Select is loading externally or not (such as options being loaded)
joinValuesbooleanfalsejoin multiple values into a single hidden input using the delimiter
labelKeystring'label'the option property to use for the label
matchPosstring'any'(any, start) match the start or entire string when filtering
matchPropstring'any'(any, label, value) which option property to filter on
menuBuffernumber0buffer of px between the base of the dropdown and the viewport to shift if menu doesnt fit in viewport
menuContainerStyleobjectundefinedoptional style to apply to the menu container
menuRendererfunctionundefinedRenders a custom menu with options; accepts the following named parameters: menuRenderer({ focusedOption, focusOption, options, selectValue, valueArray })
menuStyleobjectundefinedoptional style to apply to the menu
multibooleanundefinedmulti-value input
namestringundefinedfield name, for hidden <input /> tag
noResultsTextstring'No results found'placeholder displayed when there are no matching search results or a falsy value to hide it (can also be a react component)
onBlurfunctionundefinedonBlur handler: function(event) {}
onBlurResetsInputbooleantrueWhether to clear input on blur or not. If set to false, it only works if onCloseResetsInput is false as well.
onChangefunctionundefinedonChange handler: function(newOption) {}
onClosefunctionundefinedhandler for when the menu closes: function () {}
onCloseResetsInputbooleantruewhether to clear input when closing the menu through the arrow
onFocusfunctionundefinedonFocus handler: function(event) {}
onInputChangefunctionundefinedonInputChange handler/interceptor: function(inputValue: string): string
onInputKeyDownfunctionundefinedinput keyDown handler; call event.preventDefault() to override default Select behaviour: function(event) {}
onMenuScrollToBottomfunctionundefinedcalled when the menu is scrolled to the bottom
onOpenfunctionundefinedhandler for when the menu opens: function () {}
onSelectResetsInputbooleantruewhether the input value should be reset when options are selected. Also input value will be set to empty if 'onSelectResetsInput=true' and Select will get new value that not equal previous value.
onValueClickfunctionundefinedonClick handler for value labels: function (value, event) {}
openOnClickbooleantrueopen the options menu when the control is clicked (requires searchable = true)
openOnFocusbooleanfalseopen the options menu when the control gets focus
optionClassName: stringundefinedadditional class(es) to apply to the
optionComponentfunctionundefinedoption component to render in dropdown
optionRendererfunctionundefinedcustom function to render the options in the menu
optionsarrayundefinedarray of options
removeSelectedbooleantruewhether the selected option is removed from the dropdown on multi selects
pageSizenumber5number of options to jump when using page up/down keys
placeholderstring or node'Select …'field placeholder, displayed when there's no value
requiredbooleanfalseapplies HTML5 required attribute when needed
resetValueanynullvalue to set when the control is cleared
rtlbooleanfalseuse react-select in right-to-left direction
scrollMenuIntoViewbooleantruewhether the viewport will shift to display the entire menu when engaged
searchablebooleantruewhether to enable searching feature or not
searchPromptTextstring or node'Type to search'label to prompt for search input
simpleValuebooleanfalsepass the value to onChange as a string
styleobjectundefinedoptional styles to apply to the control
tabIndexstring or numberundefinedtabIndex of the control
tabSelectsValuebooleantruewhether to select the currently focused value when the [tab] key is pressed
trimFilterbooleanfalsewhether to trim whitespace from the filter value
valueanyundefinedinitial field value
valueComponentfunctionfunction which returns a custom way to render/manage the value selected <CustomValue />
valueKeystring'value'the option property to use for the value
valueRendererfunctionundefinedfunction which returns a custom way to render the value selected function (option) {}
wrapperStyleobjectundefinedoptional styles to apply to the component wrapper

Async Props

PropertyTypeDefaultDescription
autoloadbooleantrueautomatically call the loadOptions prop on-mount
cacheobjectundefinedSets the cache object used for options. Set to false if you would like to disable caching.
loadingPlaceholderstring or node'Loading…'label to prompt for loading search result
loadOptionsfunctionundefinedfunction that returns a promise or calls a callback with the options: function(input, [callback])

Creatable properties

PropertyTypeDescription
childrenfunctionChild function responsible for creating the inner Select component. This component can be used to compose HOCs (eg Creatable and Async). Expected signature: (props: Object): PropTypes.element
isOptionUniquefunctionSearches for any matching option within the set of options. This function prevents duplicate options from being created. By default this is a basic, case-sensitive comparison of label and value. Expected signature: ({ option: Object, options: Array, labelKey: string, valueKey: string }): boolean
isValidNewOptionfunctionDetermines if the current input text represents a valid option. By default any non-empty string will be considered valid. Expected signature: ({ label: string }): boolean
newOptionCreatorfunctionFactory to create new option. Expected signature: ({ label: string, labelKey: string, valueKey: string }): Object
onNewOptionClickfunctionnew option click handler, it calls when new option has been selected. function(option) {}
shouldKeyDownEventCreateNewOptionfunctionDecides if a keyDown event (eg its keyCode) should result in the creation of a new option. ENTER, TAB and comma keys create new options by default. Expected signature: ({ keyCode: number }): boolean
promptTextCreatorfunctionFactory for overriding default option creator prompt label. By default it will read 'Create option "{label}"'. Expected signature: (label: String): String

Methods

Use the focus() method to give the control focus. All other methods on <Select> elements should be considered private.

// focuses the input element
<instance>.focus();

Contributing

See our CONTRIBUTING.md for information on how to contribute.

Thanks to the projects this was inspired by: Selectize (in terms of behaviour and user experience), React-Autocomplete (as a quality React Combobox implementation), as well as other select controls including Chosen and Select2.

License

MIT Licensed. Copyright (c) Jed Watson 2018.

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文