react-select

前端 表单辅助
为 React JS 打造的包含多选、自动完成、ajax 支持的下拉框

NPM Build Status Coverage Status

React-Select

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

New version 1.0.0-beta

I've nearly completed a major rewrite of this component (see issue #568 for details and progress). The new code has been merged into master, and react-select@1.0.0-beta has been published to npm and bower.

1.0.0 has some breaking changes. The documentation below still needs to be updated for the new API; notes on the changes can be found in CHANGES.md and will be finalised into HISTORY.md soon.

Our tests need some major updates to work with the new API (see #571) and are causing the build to fail, but the component is stable and robust in actual usage.

Testing, feedback and PRs for the new version are appreciated.

Demo & Examples

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

The live demo is still running v0.9.1.

To build the new 1.0.0 examples locally, clone this repo then run:

npm install
npm start

Then open localhost:8000 in a browser.

Installation

The easiest way to use React-Select is to install it from NPM and include it in your own React build process (using Browserify, etc).

npm install react-select --save

At this point you can import react-select and its styles in your application as follows:

import Select from 'react-select';

// Be sure to include styles at some point, probably during your bootstrapping
import 'react-select/dist/react-select.css';

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

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://npmcdn.com/classnames/index.js"></script>
<script src="https://npmcdn.com/react-input-autosize/dist/react-input-autosize.js"></script>
<script src="https://npmcdn.com/react-select/dist/react-select.js"></script>

<link rel="stylesheet" href="https://npmcdn.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 set to either a string or a number.

When the value is changed, onChange(selectedValueOrValues) will fire.

var Select = require('react-select');

var options = [
    { value: 'one', label: 'One' },
    { value: 'two', label: 'Two' }
];

function logChange(val) {
    console.log("Selected: " + val);
}

<Select
    name="form-field-name"
    value="one"
    options={options}
    onChange={logChange}
/>

Multiselect options

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

  • Selected options will be removed from the dropdown menu
  • The selected values are submitted in multiple <input type="hidden"> fields, use joinValues 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. Setting allowCreate to true allows new options to be created if they do not already exist. NOTE: allowCreate is not implemented in 1.0.0-beta, if you need this option please stay on 0.9.x.
  • 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

Async options

If you want to load options asynchronously, instead of providing an options Array, 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.

var Select = require('react-select');

var getOptions = function(input, callback) {
    setTimeout(function() {
        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);
};

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

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 Select 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 };
    });
}

<Select.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.

var Select = require('react-select');

var isLoadingExternally = true;

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

Filtering options

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

  • 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

matchProp and matchPos both default to "any". ignoreCase 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 and ignoreCase options.
  • filterOptions: function(Array options, String filter, Array currentValues) returns Array filteredOptions. Will override filterOption, matchPos, matchProp and ignoreCase options.

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

Effeciently 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:

Parameter Type Description
focusedOption Object The currently focused option; should be visible in the menu by default.
focusOption Function Callback to focus a new option; receives the option as a parameter.
labelKey String Option labels are accessible with this string key.
options Array<Object> Ordered array of options to render.
selectValue Function Callback to select a new option; receives the option as a parameter.
valueArray Array<Object> Array of currently selected options.

Updating input values with onInputChange

You can manipulate the input using the onInputChange and returning a new 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}
/>

Further options

Property    |   Type        |   Default     |   Description

:-----------------------|:--------------|:--------------|:-------------------------------- addLabelText | string | 'Add "{label}"?' | text to display when allowCreate is true allowCreate | bool | false | allow new options to be created in multi mode (displays an "Add \

Methods

Right now there's simply a focus() method that gives the control focus. All other methods on <Select> elements should be considered private and prone to change.

// 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 2016.

react-select 相关推荐
对于该库,你有要推荐的内容么?点此提交推荐
请文明评论,与人为善,比聪明更重要!
评论