500tech-react-select 中文文档教程

发布于 9年前 浏览 34 项目主页 更新于 3年前

构建状态Coverage Status

React-Select

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

Demo & Examples

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

要在本地构建示例,请运行:

npm install
gulp dev

然后打开 localhost:8000 在浏览器中。

Project Status

这个项目非常稳定,可以用于生产,但是有计划对其进行改进,包括:

  • CSS Styles and theme support (working, could be improved)
  • Documentation website (currently just examples)
  • Custom options rendering

它松散地基于 Selectize (在行为和用户体验方面)和 React-Autocomplete(作为本机 React Combobox 实现),以及其他选择控件,包括 ChosenSelect2。

Installation

使用 React-Select 最简单的方法是从 NPM 安装它并将其包含在您自己的 React 构建过程中(使用 Browserify 等)。

npm install react-select --save

您还可以通过在页面中包含 dist/select.jsdist/default.css 来使用独立构建。 如果您使用它,请确保您已经包含以下依赖项:

Usage

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

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

每个选项的 value 属性应设置为字符串或数字。

当值更改时,onChange(newValue, [selectedOptions]) 将触发。

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

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

  • Selected options will be removed from the dropdown menu
  • The values of the selected items are joined using the delimiter property to create the input value
  • A simple value, if provided, will be split using the delimiter property
  • The onChange event provides an array of the selected options as the second argument
  • The first argument to onChange is always a string, regardless of whether the values of the selected options are numbers or strings

Async options

如果你想异步加载选项,而不是提供一个 options 数组,提供一个 asyncOptions 函数。

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

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

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

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

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
    name="form-field-name"
    value="one"
    asyncOptions={getOptions}
/>

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

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

Advanced filters

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

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

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

Further options

Property            |   Type        |   Description

:--------------------|:------------|:-------- ---------------------- 价值 | 任何| 初始字段值 值渲染器 | 功能 | 返回自定义方式来呈现所选值的函数 多 | 布尔 | 多值输入 禁用 | 布尔 | 选择是否被禁用 选项 | 数组 | 选项数组 选项渲染器 | 功能 | 该函数返回一种自定义方式来呈现菜单中的选项 分隔符 | 字符串 | 用于连接多个值的分隔符 异步选项 | 功能 | 调用以获取选项的函数 自动加载 | 布尔 | 是否自动加载默认的异步选项集 禁用缓存 | 布尔 | 禁用 asyncOptions 的选项缓存 占位符 | 字符串 | 字段占位符,没有值时显示 没有结果文本 | 字符串 | 没有匹配的搜索结果时显示的占位符 可清除 | 布尔 | 是否可以重置值 清除值文本 | 字符串 | “清除”控件的标题 清除所有文本 | 字符串 | 多时“清除”控件的标题:true 可搜索 | 布尔 | 是否启用搜索功能 搜索提示文本 | 字符串 | 提示搜索输入的标签 姓名 | 字符串 | 字段名,用于隐藏的 标签 改变 | 功能 | onChange 处理程序:函数(新值){} 聚焦 | 功能 | onFocus 处理程序:函数(事件){} 模糊 | 功能 | onBlur 处理程序:函数(事件){} 类名 | 字符串 | 外部元素的类名 过滤器选项 | 功能 | 过滤单个选项的方法:function(option, filterString) 过滤器选项 | 功能 | 过滤选项数组的方法:function([options], filterString, [values]) 匹配位置 | 字符串 | (any, start) 过滤时匹配开始或整个字符串 匹配道具 | 字符串 | (any, label, value) 要过滤的选项属性 忽略大小写 | 布尔 | 是否进行不区分大小写的过滤 输入道具 | 对象 | 输入的自定义属性(在选择控件中)例如:{'data-foo': 'bar'} 退格删除 | 布尔 | 当没有输入值时,按退格键是否删除最后一项

Contributing

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

License

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

Build StatusCoverage Status

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

To build the examples locally, run:

npm install
gulp dev

Then open localhost:8000 in a browser.

Project Status

This project is quite stable and ready for production use, however there are plans to improve it including:

  • CSS Styles and theme support (working, could be improved)
  • Documentation website (currently just examples)
  • Custom options rendering

It's loosely based on Selectize (in terms of behaviour and user experience) and React-Autocomplete (as a native React Combobox implementation), as well as other select controls including Chosen and Select2.

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

You can also use the standalone build by including dist/select.js and dist/default.css in your page. If you use this, make sure you have already included the following dependencies:

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(newValue, [selectedOptions]) 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 values of the selected items are joined using the delimiter property to create the input value
  • A simple value, if provided, will be split using the delimiter property
  • The onChange event provides an array of the selected options as the second argument
  • The first argument to onChange is always a string, regardless of whether the values of the selected options are numbers or strings

Async options

If you want to load options asynchronously, instead of providing an options Array, provide a asyncOptions 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 cacheAsyncResults 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
    name="form-field-name"
    value="one"
    asyncOptions={getOptions}
/>

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.

Further options

Property            |   Type        |   Description

:-----------------------|:--------------|:-------------------------------- value | any | initial field value valueRenderer | func | function which returns a custom way to render the value selected multi | bool | multi-value input disabled | bool | whether the Select is disabled or not options | array | array of options optionRenderer | func | function which returns a custom way to render the options in the menu delimiter | string | delimiter to use to join multiple values asyncOptions | func | function to call to get options autoload | bool | whether to auto-load the default async options set disableCache | bool | disables the options cache for asyncOptions placeholder | string | field placeholder, displayed when there's no value noResultsText | string | placeholder displayed when there are no matching search results clearable | bool | should it be possible to reset value clearValueText | string | title for the "clear" control clearAllText | string | title for the "clear" control when multi: true searchable | bool | whether to enable searching feature or not searchPromptText | string | label to prompt for search input name | string | field name, for hidden tag onChange | func | onChange handler: function(newValue) {} onFocus | func | onFocus handler: function(event) {} onBlur | func | onBlur handler: function(event) {} className | string | className for the outer element filterOption | func | method to filter a single option: function(option, filterString) filterOptions | func | method to filter the options array: function([options], filterString, [values]) matchPos | string | (any, start) match the start or entire string when filtering matchProp | string | (any, label, value) which option property to filter on ignoreCase | bool | whether to perform case-insensitive filtering inputProps | object | custom attributes for the Input (in the Select-control) e.g: {'data-foo': 'bar'} backspaceRemoves | bool | whether pressing backspace removes the last item when there is no input value

Contributing

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

License

MIT Licensed. Copyright (c) Jed Watson 2015.

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