Select选择器

下拉选择器。

何时使用

  • 弹出一个下拉菜单给用户选择操作,用于代替原生的选择器,或者需要一个更优雅的多选器时。

  • 当选项少时(少于 5 项),建议直接将选项平铺,使用 Radio 是更好的选择。

代码演示

Select选择器 - 图1

基本使用

基本使用。

  1. import { Select } from 'antd';
  2. const { Option } = Select;
  3. function handleChange(value) {
  4. console.log(`selected ${value}`);
  5. }
  6. ReactDOM.render(
  7. <div>
  8. <Select defaultValue="lucy" style={{ width: 120 }} onChange={handleChange}>
  9. <Option value="jack">Jack</Option>
  10. <Option value="lucy">Lucy</Option>
  11. <Option value="disabled" disabled>
  12. Disabled
  13. </Option>
  14. <Option value="Yiminghe">yiminghe</Option>
  15. </Select>
  16. <Select defaultValue="lucy" style={{ width: 120 }} disabled>
  17. <Option value="lucy">Lucy</Option>
  18. </Select>
  19. <Select defaultValue="lucy" style={{ width: 120 }} loading>
  20. <Option value="lucy">Lucy</Option>
  21. </Select>
  22. </div>,
  23. mountNode,
  24. );

Select选择器 - 图2

多选

多选,从已有条目中选择。

  1. import { Select } from 'antd';
  2. const { Option } = Select;
  3. const children = [];
  4. for (let i = 10; i < 36; i++) {
  5. children.push(<Option key={i.toString(36) + i}>{i.toString(36) + i}</Option>);
  6. }
  7. function handleChange(value) {
  8. console.log(`selected ${value}`);
  9. }
  10. ReactDOM.render(
  11. <Select
  12. mode="multiple"
  13. style={{ width: '100%' }}
  14. placeholder="Please select"
  15. defaultValue={['a10', 'c12']}
  16. onChange={handleChange}
  17. >
  18. {children}
  19. </Select>,
  20. mountNode,
  21. );

Select选择器 - 图3

定制回填内容

使用 optionLabelProp 指定回填到选择框的 Option 属性。

  1. import { Select } from 'antd';
  2. const { Option } = Select;
  3. function handleChange(value) {
  4. console.log(`selected ${value}`);
  5. }
  6. ReactDOM.render(
  7. <Select
  8. mode="multiple"
  9. style={{ width: '100%' }}
  10. placeholder="select one country"
  11. defaultValue={['china']}
  12. onChange={handleChange}
  13. optionLabelProp="label"
  14. >
  15. <Option value="china" label="China">
  16. <span role="img" aria-label="China">
  17. 🇨🇳
  18. </span>
  19. China (中国)
  20. </Option>
  21. <Option value="usa" label="USA">
  22. <span role="img" aria-label="USA">
  23. 🇺🇸
  24. </span>
  25. USA (美国)
  26. </Option>
  27. <Option value="japan" label="Japan">
  28. <span role="img" aria-label="Japan">
  29. 🇯🇵
  30. </span>
  31. Japan (日本)
  32. </Option>
  33. <Option value="korea" label="Korea">
  34. <span role="img" aria-label="Korea">
  35. 🇰🇷
  36. </span>
  37. Korea (韩国)
  38. </Option>
  39. </Select>,
  40. mountNode,
  41. );
  1. span[role="img"] {
  2. margin-right: 6px;
  3. }

Select选择器 - 图4

分组

OptGroup 进行选项分组。

  1. import { Select } from 'antd';
  2. const { Option, OptGroup } = Select;
  3. function handleChange(value) {
  4. console.log(`selected ${value}`);
  5. }
  6. ReactDOM.render(
  7. <Select defaultValue="lucy" style={{ width: 200 }} onChange={handleChange}>
  8. <OptGroup label="Manager">
  9. <Option value="jack">Jack</Option>
  10. <Option value="lucy">Lucy</Option>
  11. </OptGroup>
  12. <OptGroup label="Engineer">
  13. <Option value="Yiminghe">yiminghe</Option>
  14. </OptGroup>
  15. </Select>,
  16. mountNode,
  17. );

Select选择器 - 图5

搜索框

搜索和远程数据结合。

  1. import { Select } from 'antd';
  2. import jsonp from 'fetch-jsonp';
  3. import querystring from 'querystring';
  4. const { Option } = Select;
  5. let timeout;
  6. let currentValue;
  7. function fetch(value, callback) {
  8. if (timeout) {
  9. clearTimeout(timeout);
  10. timeout = null;
  11. }
  12. currentValue = value;
  13. function fake() {
  14. const str = querystring.encode({
  15. code: 'utf-8',
  16. q: value,
  17. });
  18. jsonp(`https://suggest.taobao.com/sug?${str}`)
  19. .then(response => response.json())
  20. .then(d => {
  21. if (currentValue === value) {
  22. const { result } = d;
  23. const data = [];
  24. result.forEach(r => {
  25. data.push({
  26. value: r[0],
  27. text: r[0],
  28. });
  29. });
  30. callback(data);
  31. }
  32. });
  33. }
  34. timeout = setTimeout(fake, 300);
  35. }
  36. class SearchInput extends React.Component {
  37. state = {
  38. data: [],
  39. value: undefined,
  40. };
  41. handleSearch = value => {
  42. if (value) {
  43. fetch(value, data => this.setState({ data }));
  44. } else {
  45. this.setState({ data: [] });
  46. }
  47. };
  48. handleChange = value => {
  49. this.setState({ value });
  50. };
  51. render() {
  52. const options = this.state.data.map(d => <Option key={d.value}>{d.text}</Option>);
  53. return (
  54. <Select
  55. showSearch
  56. value={this.state.value}
  57. placeholder={this.props.placeholder}
  58. style={this.props.style}
  59. defaultActiveFirstOption={false}
  60. showArrow={false}
  61. filterOption={false}
  62. onSearch={this.handleSearch}
  63. onChange={this.handleChange}
  64. notFoundContent={null}
  65. >
  66. {options}
  67. </Select>
  68. );
  69. }
  70. }
  71. ReactDOM.render(<SearchInput placeholder="input search text" style={{ width: 200 }} />, mountNode);

Select选择器 - 图6

自动分词

试下复制 露西,杰克 到输入框里。只在 tags 和 multiple 模式下可用。

  1. import { Select } from 'antd';
  2. const { Option } = Select;
  3. const children = [];
  4. for (let i = 10; i < 36; i++) {
  5. children.push(<Option key={i.toString(36) + i}>{i.toString(36) + i}</Option>);
  6. }
  7. function handleChange(value) {
  8. console.log(`selected ${value}`);
  9. }
  10. ReactDOM.render(
  11. <Select mode="tags" style={{ width: '100%' }} onChange={handleChange} tokenSeparators={[',']}>
  12. {children}
  13. </Select>,
  14. mountNode,
  15. );

Select选择器 - 图7

扩展菜单

使用 dropdownRender 对下拉菜单进行自由扩展。自定义内容点击时会关闭浮层,如果不喜欢关闭,可以添加 onMouseDown={e => e.preventDefault()} 进行阻止(更多详情见 #13448)。

  1. import { Select, Icon, Divider } from 'antd';
  2. const { Option } = Select;
  3. let index = 0;
  4. class App extends React.Component {
  5. state = {
  6. items: ['jack', 'lucy'],
  7. };
  8. addItem = () => {
  9. console.log('addItem');
  10. const { items } = this.state;
  11. this.setState({
  12. items: [...items, `New item ${index++}`],
  13. });
  14. };
  15. render() {
  16. const { items } = this.state;
  17. return (
  18. <Select
  19. style={{ width: 240 }}
  20. placeholder="custom dropdown render"
  21. dropdownRender={menu => (
  22. <div>
  23. {menu}
  24. <Divider style={{ margin: '4px 0' }} />
  25. <div
  26. style={{ padding: '4px 8px', cursor: 'pointer' }}
  27. onMouseDown={e => e.preventDefault()}
  28. onClick={this.addItem}
  29. >
  30. <Icon type="plus" /> Add item
  31. </div>
  32. </div>
  33. )}
  34. >
  35. {items.map(item => (
  36. <Option key={item}>{item}</Option>
  37. ))}
  38. </Select>
  39. );
  40. }
  41. }
  42. ReactDOM.render(<App />, mountNode);

Select选择器 - 图8

带搜索框

展开后可对选项进行搜索。

  1. import { Select } from 'antd';
  2. const { Option } = Select;
  3. function onChange(value) {
  4. console.log(`selected ${value}`);
  5. }
  6. function onBlur() {
  7. console.log('blur');
  8. }
  9. function onFocus() {
  10. console.log('focus');
  11. }
  12. function onSearch(val) {
  13. console.log('search:', val);
  14. }
  15. ReactDOM.render(
  16. <Select
  17. showSearch
  18. style={{ width: 200 }}
  19. placeholder="Select a person"
  20. optionFilterProp="children"
  21. onChange={onChange}
  22. onFocus={onFocus}
  23. onBlur={onBlur}
  24. onSearch={onSearch}
  25. filterOption={(input, option) =>
  26. option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
  27. }
  28. >
  29. <Option value="jack">Jack</Option>
  30. <Option value="lucy">Lucy</Option>
  31. <Option value="tom">Tom</Option>
  32. </Select>,
  33. mountNode,
  34. );

Select选择器 - 图9

三种大小

三种大小的选择框,当 size 分别为 largesmall 时,输入框高度为 40px24px ,默认高度为 32px

  1. import { Select, Radio } from 'antd';
  2. const { Option } = Select;
  3. const children = [];
  4. for (let i = 10; i < 36; i++) {
  5. children.push(<Option key={i.toString(36) + i}>{i.toString(36) + i}</Option>);
  6. }
  7. function handleChange(value) {
  8. console.log(`Selected: ${value}`);
  9. }
  10. class SelectSizesDemo extends React.Component {
  11. state = {
  12. size: 'default',
  13. };
  14. handleSizeChange = e => {
  15. this.setState({ size: e.target.value });
  16. };
  17. render() {
  18. const { size } = this.state;
  19. return (
  20. <div>
  21. <Radio.Group value={size} onChange={this.handleSizeChange}>
  22. <Radio.Button value="large">Large</Radio.Button>
  23. <Radio.Button value="default">Default</Radio.Button>
  24. <Radio.Button value="small">Small</Radio.Button>
  25. </Radio.Group>
  26. <br />
  27. <br />
  28. <Select size={size} defaultValue="a1" onChange={handleChange} style={{ width: 200 }}>
  29. {children}
  30. </Select>
  31. <br />
  32. <Select
  33. mode="multiple"
  34. size={size}
  35. placeholder="Please select"
  36. defaultValue={['a10', 'c12']}
  37. onChange={handleChange}
  38. style={{ width: '100%' }}
  39. >
  40. {children}
  41. </Select>
  42. <br />
  43. <Select
  44. mode="tags"
  45. size={size}
  46. placeholder="Please select"
  47. defaultValue={['a10', 'c12']}
  48. onChange={handleChange}
  49. style={{ width: '100%' }}
  50. >
  51. {children}
  52. </Select>
  53. </div>
  54. );
  55. }
  56. }
  57. ReactDOM.render(<SelectSizesDemo />, mountNode);
  1. .code-box-demo .ant-select {
  2. margin: 0 8px 10px 0;
  3. }
  4. #components-select-demo-search-box .code-box-demo .ant-select {
  5. margin: 0;
  6. }

Select选择器 - 图10

标签

tags select,随意输入的内容(scroll the menu)

  1. import { Select } from 'antd';
  2. const { Option } = Select;
  3. const children = [];
  4. for (let i = 10; i < 36; i++) {
  5. children.push(<Option key={i.toString(36) + i}>{i.toString(36) + i}</Option>);
  6. }
  7. function handleChange(value) {
  8. console.log(`selected ${value}`);
  9. }
  10. ReactDOM.render(
  11. <Select mode="tags" style={{ width: '100%' }} placeholder="Tags Mode" onChange={handleChange}>
  12. {children}
  13. </Select>,
  14. mountNode,
  15. );

Select选择器 - 图11

联动

省市联动是典型的例子。

推荐使用 Cascader 组件。

  1. import { Select } from 'antd';
  2. const { Option } = Select;
  3. const provinceData = ['Zhejiang', 'Jiangsu'];
  4. const cityData = {
  5. Zhejiang: ['Hangzhou', 'Ningbo', 'Wenzhou'],
  6. Jiangsu: ['Nanjing', 'Suzhou', 'Zhenjiang'],
  7. };
  8. class App extends React.Component {
  9. state = {
  10. cities: cityData[provinceData[0]],
  11. secondCity: cityData[provinceData[0]][0],
  12. };
  13. handleProvinceChange = value => {
  14. this.setState({
  15. cities: cityData[value],
  16. secondCity: cityData[value][0],
  17. });
  18. };
  19. onSecondCityChange = value => {
  20. this.setState({
  21. secondCity: value,
  22. });
  23. };
  24. render() {
  25. const { cities } = this.state;
  26. return (
  27. <div>
  28. <Select
  29. defaultValue={provinceData[0]}
  30. style={{ width: 120 }}
  31. onChange={this.handleProvinceChange}
  32. >
  33. {provinceData.map(province => (
  34. <Option key={province}>{province}</Option>
  35. ))}
  36. </Select>
  37. <Select
  38. style={{ width: 120 }}
  39. value={this.state.secondCity}
  40. onChange={this.onSecondCityChange}
  41. >
  42. {cities.map(city => (
  43. <Option key={city}>{city}</Option>
  44. ))}
  45. </Select>
  46. </div>
  47. );
  48. }
  49. }
  50. ReactDOM.render(<App />, mountNode);

Select选择器 - 图12

获得选项的文本

默认情况下 onChange 里只能拿到 value,如果需要拿到选中的节点文本 label,可以使用 labelInValue 属性。

选中项的 label 会被包装到 value 中传递给 onChange 等函数,此时 value 是一个对象。

  1. import { Select } from 'antd';
  2. const { Option } = Select;
  3. function handleChange(value) {
  4. console.log(value); // { key: "lucy", label: "Lucy (101)" }
  5. }
  6. ReactDOM.render(
  7. <Select
  8. labelInValue
  9. defaultValue={{ key: 'lucy' }}
  10. style={{ width: 120 }}
  11. onChange={handleChange}
  12. >
  13. <Option value="jack">Jack (100)</Option>
  14. <Option value="lucy">Lucy (101)</Option>
  15. </Select>,
  16. mountNode,
  17. );

Select选择器 - 图13

搜索用户

一个带有远程搜索,防抖控制,请求时序控制,加载状态的多选示例。

  1. import { Select, Spin } from 'antd';
  2. import debounce from 'lodash/debounce';
  3. const { Option } = Select;
  4. class UserRemoteSelect extends React.Component {
  5. constructor(props) {
  6. super(props);
  7. this.lastFetchId = 0;
  8. this.fetchUser = debounce(this.fetchUser, 800);
  9. }
  10. state = {
  11. data: [],
  12. value: [],
  13. fetching: false,
  14. };
  15. fetchUser = value => {
  16. console.log('fetching user', value);
  17. this.lastFetchId += 1;
  18. const fetchId = this.lastFetchId;
  19. this.setState({ data: [], fetching: true });
  20. fetch('https://randomuser.me/api/?results=5')
  21. .then(response => response.json())
  22. .then(body => {
  23. if (fetchId !== this.lastFetchId) {
  24. // for fetch callback order
  25. return;
  26. }
  27. const data = body.results.map(user => ({
  28. text: `${user.name.first} ${user.name.last}`,
  29. value: user.login.username,
  30. }));
  31. this.setState({ data, fetching: false });
  32. });
  33. };
  34. handleChange = value => {
  35. this.setState({
  36. value,
  37. data: [],
  38. fetching: false,
  39. });
  40. };
  41. render() {
  42. const { fetching, data, value } = this.state;
  43. return (
  44. <Select
  45. mode="multiple"
  46. labelInValue
  47. value={value}
  48. placeholder="Select users"
  49. notFoundContent={fetching ? <Spin size="small" /> : null}
  50. filterOption={false}
  51. onSearch={this.fetchUser}
  52. onChange={this.handleChange}
  53. style={{ width: '100%' }}
  54. >
  55. {data.map(d => (
  56. <Option key={d.value}>{d.text}</Option>
  57. ))}
  58. </Select>
  59. );
  60. }
  61. }
  62. ReactDOM.render(<UserRemoteSelect />, mountNode);

Select选择器 - 图14

隐藏已选择选项

隐藏下拉列表中已选择的选项。

  1. import { Select } from 'antd';
  2. const OPTIONS = ['Apples', 'Nails', 'Bananas', 'Helicopters'];
  3. class SelectWithHiddenSelectedOptions extends React.Component {
  4. state = {
  5. selectedItems: [],
  6. };
  7. handleChange = selectedItems => {
  8. this.setState({ selectedItems });
  9. };
  10. render() {
  11. const { selectedItems } = this.state;
  12. const filteredOptions = OPTIONS.filter(o => !selectedItems.includes(o));
  13. return (
  14. <Select
  15. mode="multiple"
  16. placeholder="Inserted are removed"
  17. value={selectedItems}
  18. onChange={this.handleChange}
  19. style={{ width: '100%' }}
  20. >
  21. {filteredOptions.map(item => (
  22. <Select.Option key={item} value={item}>
  23. {item}
  24. </Select.Option>
  25. ))}
  26. </Select>
  27. );
  28. }
  29. }
  30. ReactDOM.render(<SelectWithHiddenSelectedOptions />, mountNode);

API

  1. <Select>
  2. <Select.Option value="lucy">lucy</Select.Option>
  3. </Select>

Select props

参数说明类型默认值版本
allowClear支持清除booleanfalse
autoClearSearchValue是否在选中项后清空搜索框,只在 modemultipletags 时有效。booleantrue3.10.0
autoFocus默认获取焦点booleanfalse
defaultActiveFirstOption是否默认高亮第一个选项。booleantrue
defaultValue指定默认选中的条目string|string[]\number|number[]\LabeledValue|LabeledValue[]-
disabled是否禁用booleanfalse
dropdownClassName下拉菜单的 className 属性string-
dropdownMatchSelectWidth下拉菜单和选择器同宽booleantrue
dropdownRender自定义下拉框内容(menuNode: ReactNode, props) => ReactNode-3.11.0
dropdownStyle下拉菜单的 style 属性object-
dropdownMenuStyledropdown 菜单自定义样式object-
filterOption是否根据输入项进行筛选。当其为一个函数时,会接收 inputValue option 两个参数,当 option 符合筛选条件时,应返回 true,反之则返回 falseboolean or function(inputValue, option)true
firstActiveValue默认高亮的选项string|string[]-
getPopupContainer菜单渲染父节点。默认渲染到 body 上,如果你遇到菜单滚动定位问题,试试修改为滚动的区域,并相对其定位。示例Function(triggerNode)() => document.body
labelInValue是否把每个选项的 label 包装到 value 中,会把 Select 的 value 类型从 string 变为 {key: string, label: ReactNode} 的格式booleanfalse
maxTagCount最多显示多少个 tagnumber-
maxTagTextLength最大显示的 tag 文本长度number-3.18.0
maxTagPlaceholder隐藏 tag 时显示的内容ReactNode/function(omittedValues)-
mode设置 Select 的模式为多选或标签'multiple' | 'tags'-
notFoundContent当下拉列表为空时显示的内容string'Not Found'
optionFilterProp搜索时过滤对应的 option 属性,如设置为 children 表示对内嵌内容进行搜索。示例stringvalue
optionLabelProp回填到选择框的 Option 的属性值,默认是 Option 的子元素。比如在子元素需要高亮效果时,此值可以设为 valuestringchildren (combobox 模式下为 value
placeholder选择框默认文字string-
showArrow是否显示下拉小箭头booleantrue3.2.1
showSearch使单选模式可搜索booleanfalse
size选择框大小,可选 large smallstringdefault
suffixIcon自定义的选择框后缀图标ReactNode-3.10.0
removeIcon自定义的多选框清除图标ReactNode-3.11.0
clearIcon自定义的多选框清空图标ReactNode-3.11.0
menuItemSelectedIcon自定义多选时当前选中的条目图标ReactNode-3.11.0
tokenSeparators在 tags 和 multiple 模式下自动分词的分隔符string[]
value指定当前选中的条目string|string[]\number|number[]\LabeledValue|LabeledValue[]-
onBlur失去焦点时回调function-
onChange选中 option,或 input 的 value 变化(combobox 模式下)时,调用此函数function(value, option:Option/Array<Option>)-
onDeselect取消选中时调用,参数为选中项的 value (或 key) 值,仅在 multiple 或 tags 模式下生效function(string|number|LabeledValue)-
onFocus获得焦点时回调function-
onInputKeyDown按键按下时回调function-3.1.0
onMouseEnter鼠标移入时回调function-
onMouseLeave鼠标移出时回调function-
onPopupScroll下拉列表滚动时的回调function-
onSearch文本框值变化时回调function(value: string)
onSelect被选中时调用,参数为选中项的 value (或 key) 值function(string|number|LabeledValue, option:Option)-
defaultOpen是否默认展开下拉菜单boolean-3.9.3
open是否展开下拉菜单boolean-3.9.0
onDropdownVisibleChange展开下拉菜单的回调 (3.9.0 后支持)function(open)-3.9.0
loading加载中状态Booleanfalse3.11.0

注意,如果发现下拉菜单跟随页面滚动,或者需要在其他弹层中触发 Select,请尝试使用 getPopupContainer={triggerNode => triggerNode.parentElement} 将下拉弹层渲染节点固定在触发器的父元素中。

Select Methods

名称说明版本
blur()取消焦点
focus()获取焦点

Option props

参数说明类型默认值版本
disabled是否禁用booleanfalse
key和 value 含义一致。如果 React 需要你设置此项,此项值与 value 的值相同,然后可以省略 value 设置string
title选中该 Option 后,Select 的 titlestring-
value默认根据此属性值进行筛选string|number-
classNameOption 器类名string-3.10.1

OptGroup props

参数说明类型默认值版本
keystring-
label组名string|React.Element

FAQ

点击 dropdownRender 里的内容浮层关闭怎么办?

看下 dropdownRender 例子 里的说明。