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. <>
  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. <Select defaultValue="lucy" style={{ width: 120 }} allowClear>
  23. <Option value="lucy">Lucy</Option>
  24. </Select>
  25. </>,
  26. mountNode,
  27. );

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. <>
  12. <Select
  13. mode="multiple"
  14. allowClear
  15. style={{ width: '100%' }}
  16. placeholder="Please select"
  17. defaultValue={['a10', 'c12']}
  18. onChange={handleChange}
  19. >
  20. {children}
  21. </Select>
  22. <br />
  23. <Select
  24. mode="multiple"
  25. disabled
  26. style={{ width: '100%' }}
  27. placeholder="Please select"
  28. defaultValue={['a10', 'c12']}
  29. onChange={handleChange}
  30. >
  31. {children}
  32. </Select>
  33. </>,
  34. mountNode,
  35. );

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. <div className="demo-option-label-item">
  17. <span role="img" aria-label="China">
  18. 🇨🇳
  19. </span>
  20. China (中国)
  21. </div>
  22. </Option>
  23. <Option value="usa" label="USA">
  24. <div className="demo-option-label-item">
  25. <span role="img" aria-label="USA">
  26. 🇺🇸
  27. </span>
  28. USA (美国)
  29. </div>
  30. </Option>
  31. <Option value="japan" label="Japan">
  32. <div className="demo-option-label-item">
  33. <span role="img" aria-label="Japan">
  34. 🇯🇵
  35. </span>
  36. Japan (日本)
  37. </div>
  38. </Option>
  39. <Option value="korea" label="Korea">
  40. <div className="demo-option-label-item">
  41. <span role="img" aria-label="Korea">
  42. 🇰🇷
  43. </span>
  44. Korea (韩国)
  45. </div>
  46. </Option>
  47. </Select>,
  48. mountNode,
  49. );
  1. .demo-option-label-item > span {
  2. margin-right: 6px;
  3. }

Select选择器 - 图4

标签

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选择器 - 图5

联动

省市联动是典型的例子。

推荐使用 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. const App = () => {
  9. const [cities, setCities] = React.useState(cityData[provinceData[0]]);
  10. const [secondCity, setSecondCity] = React.useState(cityData[provinceData[0]][0]);
  11. const handleProvinceChange = value => {
  12. setCities(cityData[value]);
  13. setSecondCity(cityData[value][0]);
  14. };
  15. const onSecondCityChange = value => {
  16. setSecondCity(value);
  17. };
  18. return (
  19. <>
  20. <Select defaultValue={provinceData[0]} style={{ width: 120 }} onChange={handleProvinceChange}>
  21. {provinceData.map(province => (
  22. <Option key={province}>{province}</Option>
  23. ))}
  24. </Select>
  25. <Select style={{ width: 120 }} value={secondCity} onChange={onSecondCityChange}>
  26. {cities.map(city => (
  27. <Option key={city}>{city}</Option>
  28. ))}
  29. </Select>
  30. </>
  31. );
  32. };
  33. ReactDOM.render(<App />, mountNode);

Select选择器 - 图6

获得选项的文本

默认情况下 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); // { value: "lucy", key: "lucy", label: "Lucy (101)" }
  5. }
  6. ReactDOM.render(
  7. <Select
  8. labelInValue
  9. defaultValue={{ value: '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选择器 - 图7

搜索用户

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

  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选择器 - 图8

隐藏已选择选项

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

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

Select选择器 - 图9

无边框

无边框样式。

  1. import { Select } from 'antd';
  2. const { Option } = Select;
  3. ReactDOM.render(
  4. <>
  5. <Select defaultValue="lucy" style={{ width: 120 }} bordered={false}>
  6. <Option value="jack">Jack</Option>
  7. <Option value="lucy">Lucy</Option>
  8. <Option value="Yiminghe">yiminghe</Option>
  9. </Select>
  10. <Select defaultValue="lucy" style={{ width: 120 }} disabled bordered={false}>
  11. <Option value="lucy">Lucy</Option>
  12. </Select>
  13. </>,
  14. mountNode,
  15. );

Select选择器 - 图10

带搜索框

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

  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.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选择器 - 图11

三种大小

三种大小的选择框,当 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. const SelectSizesDemo = () => {
  11. const [size, setSize] = React.useState('default');
  12. const handleSizeChange = e => {
  13. setSize(e.target.value);
  14. };
  15. return (
  16. <>
  17. <Radio.Group value={size} onChange={handleSizeChange}>
  18. <Radio.Button value="large">Large</Radio.Button>
  19. <Radio.Button value="default">Default</Radio.Button>
  20. <Radio.Button value="small">Small</Radio.Button>
  21. </Radio.Group>
  22. <br />
  23. <br />
  24. <Select size={size} defaultValue="a1" onChange={handleChange} style={{ width: 200 }}>
  25. {children}
  26. </Select>
  27. <br />
  28. <Select
  29. mode="multiple"
  30. size={size}
  31. placeholder="Please select"
  32. defaultValue={['a10', 'c12']}
  33. onChange={handleChange}
  34. style={{ width: '100%' }}
  35. >
  36. {children}
  37. </Select>
  38. <br />
  39. <Select
  40. mode="tags"
  41. size={size}
  42. placeholder="Please select"
  43. defaultValue={['a10', 'c12']}
  44. onChange={handleChange}
  45. style={{ width: '100%' }}
  46. >
  47. {children}
  48. </Select>
  49. </>
  50. );
  51. };
  52. ReactDOM.render(<SelectSizesDemo />, mountNode);
  1. .code-box-demo .ant-select {
  2. margin: 0 8px 10px 0;
  3. }
  4. .ant-row-rtl .code-box-demo .ant-select {
  5. margin: 0 0 10px 8px;
  6. }
  7. #components-select-demo-search-box .code-box-demo .ant-select {
  8. margin: 0;
  9. }

Select选择器 - 图12

带排序的搜索

在搜索模式下对过滤结果项进行排序。

  1. import { Select } from 'antd';
  2. const { Option } = Select;
  3. ReactDOM.render(
  4. <Select
  5. showSearch
  6. style={{ width: 200 }}
  7. placeholder="Search to Select"
  8. optionFilterProp="children"
  9. filterOption={(input, option) =>
  10. option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
  11. }
  12. filterSort={(optionA, optionB) =>
  13. optionA.children.toLowerCase().localeCompare(optionB.children.toLowerCase())
  14. }
  15. >
  16. <Option value="1">Not Identified</Option>
  17. <Option value="2">Closed</Option>
  18. <Option value="3">Communicated</Option>
  19. <Option value="4">Identified</Option>
  20. <Option value="5">Resolved</Option>
  21. <Option value="6">Cancelled</Option>
  22. </Select>,
  23. mountNode,
  24. );

Select选择器 - 图13

分组

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选择器 - 图14

搜索框

搜索和远程数据结合。

  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选择器 - 图15

自动分词

试下复制 露西,杰克 到输入框里。只在 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选择器 - 图16

扩展菜单

使用 dropdownRender 对下拉菜单进行自由扩展。

  1. import { Select, Divider, Input } from 'antd';
  2. import { PlusOutlined } from '@ant-design/icons';
  3. const { Option } = Select;
  4. let index = 0;
  5. class App extends React.Component {
  6. state = {
  7. items: ['jack', 'lucy'],
  8. name: '',
  9. };
  10. onNameChange = event => {
  11. this.setState({
  12. name: event.target.value,
  13. });
  14. };
  15. addItem = () => {
  16. console.log('addItem');
  17. const { items, name } = this.state;
  18. this.setState({
  19. items: [...items, name || `New item ${index++}`],
  20. name: '',
  21. });
  22. };
  23. render() {
  24. const { items, name } = this.state;
  25. return (
  26. <Select
  27. style={{ width: 240 }}
  28. placeholder="custom dropdown render"
  29. dropdownRender={menu => (
  30. <div>
  31. {menu}
  32. <Divider style={{ margin: '4px 0' }} />
  33. <div style={{ display: 'flex', flexWrap: 'nowrap', padding: 8 }}>
  34. <Input style={{ flex: 'auto' }} value={name} onChange={this.onNameChange} />
  35. <a
  36. style={{ flex: 'none', padding: '8px', display: 'block', cursor: 'pointer' }}
  37. onClick={this.addItem}
  38. >
  39. <PlusOutlined /> Add item
  40. </a>
  41. </div>
  42. </div>
  43. )}
  44. >
  45. {items.map(item => (
  46. <Option key={item}>{item}</Option>
  47. ))}
  48. </Select>
  49. );
  50. }
  51. }
  52. ReactDOM.render(<App />, mountNode);

Select选择器 - 图17

大数据

Select 使用了虚拟滚动技术,因而获得了比 3.0 更好的性能

  1. import { Select, Typography, Divider } from 'antd';
  2. const { Title } = Typography;
  3. const options = [];
  4. for (let i = 0; i < 100000; i++) {
  5. const value = `${i.toString(36)}${i}`;
  6. options.push({
  7. value,
  8. disabled: i === 10,
  9. });
  10. }
  11. function handleChange(value) {
  12. console.log(`selected ${value}`);
  13. }
  14. ReactDOM.render(
  15. <>
  16. <Title level={3}>Ant Design 4.0</Title>
  17. <Title level={4}>{options.length} Items</Title>
  18. <Select
  19. mode="multiple"
  20. style={{ width: '100%' }}
  21. placeholder="Please select"
  22. defaultValue={['a10', 'c12']}
  23. onChange={handleChange}
  24. options={options}
  25. />
  26. <Divider />
  27. <Title level={3}>Ant Design 3.0</Title>
  28. <iframe
  29. title="Ant Design 3.0 Select demo"
  30. src="https://codesandbox.io/embed/solitary-voice-m3vme?fontsize=14&hidenavigation=1&theme=dark&view=preview"
  31. style={{ width: '100%', height: 300 }}
  32. />
  33. </>,
  34. mountNode,
  35. );

Select选择器 - 图18

自定义选择标签

允许自定义选择标签的样式。

  1. import { Select, Tag } from 'antd';
  2. const options = [{ value: 'gold' }, { value: 'lime' }, { value: 'green' }, { value: 'cyan' }];
  3. function tagRender(props) {
  4. const { label, value, closable, onClose } = props;
  5. return (
  6. <Tag color={value} closable={closable} onClose={onClose} style={{ marginRight: 3 }}>
  7. {label}
  8. </Tag>
  9. );
  10. }
  11. ReactDOM.render(
  12. <Select
  13. mode="multiple"
  14. showArrow
  15. tagRender={tagRender}
  16. defaultValue={['gold', 'cyan']}
  17. style={{ width: '100%' }}
  18. options={options}
  19. />,
  20. mountNode,
  21. );

API

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

Select props

参数说明类型默认值版本
allowClear支持清除booleanfalse
autoClearSearchValue是否在选中项后清空搜索框,只在 modemultipletags 时有效booleantrue
autoFocus默认获取焦点booleanfalse
bordered是否有边框booleantrue
clearIcon自定义的多选框清空图标ReactNode-
defaultActiveFirstOption是否默认高亮第一个选项booleantrue
defaultOpen是否默认展开下拉菜单boolean-
defaultValue指定默认选中的条目string | string[]
number | number[]
LabeledValue | LabeledValue[]
-
disabled是否禁用booleanfalse
dropdownClassName下拉菜单的 className 属性string-
dropdownMatchSelectWidth下拉菜单和选择器同宽。默认将设置 min-width,当值小于选择框宽度时会被忽略。false 时会关闭虚拟滚动boolean | numbertrue
dropdownRender自定义下拉框内容(originNode: ReactNode) => ReactNode-
dropdownStyle下拉菜单的 style 属性CSSProperties-
filterOption是否根据输入项进行筛选。当其为一个函数时,会接收 inputValue option 两个参数,当 option 符合筛选条件时,应返回 true,反之则返回 falseboolean | function(inputValue, option)true
filterSort搜索时对筛选结果项的排序函数, 类似Array.sort里的compareFunction(optionA: Option, optionB: Option) => number-4.9.0
getPopupContainer菜单渲染父节点。默认渲染到 body 上,如果你遇到菜单滚动定位问题,试试修改为滚动的区域,并相对其定位。示例function(triggerNode)() => document.body
labelInValue是否把每个选项的 label 包装到 value 中,会把 Select 的 value 类型从 string 变为 { value: string, label: ReactNode } 的格式booleanfalse
listHeight设置弹窗滚动高度number256
loading加载中状态booleanfalse
maxTagCount最多显示多少个 tagnumber-
maxTagPlaceholder隐藏 tag 时显示的内容ReactNode | function(omittedValues)-
maxTagTextLength最大显示的 tag 文本长度number-
menuItemSelectedIcon自定义多选时当前选中的条目图标ReactNode-
mode设置 Select 的模式为多选或标签multiple | tags-
notFoundContent当下拉列表为空时显示的内容ReactNodeNot Found
open是否展开下拉菜单boolean-
optionFilterProp搜索时过滤对应的 option 属性,如设置为 children 表示对内嵌内容进行搜索。若通过 options 属性配置选项内容,建议设置 optionFilterProp=”label” 来对内容进行搜索。stringvalue
optionLabelProp回填到选择框的 Option 的属性值,默认是 Option 的子元素。比如在子元素需要高亮效果时,此值可以设为 value示例stringchildren
options数据化配置选项内容,相比 jsx 定义会获得更好的渲染性能{ label, value }[]-
placeholder选择框默认文本string-
removeIcon自定义的多选框清除图标ReactNode-
searchValue控制搜索文本string-
showArrow是否显示下拉小箭头boolean单选为 true,多选为 false
showSearch使单选模式可搜索booleanfalse
size选择框大小large | middle | smallmiddle
suffixIcon自定义的选择框后缀图标ReactNode-
tagRender自定义 tag 内容 render(props) => ReactNode-
tokenSeparatorstagsmultiple 模式下自动分词的分隔符string[]-
value指定当前选中的条目string | string[]
number | number[]
LabeledValue | LabeledValue[]
-
virtual设置 false 时关闭虚拟滚动booleantrue4.1.0
onBlur失去焦点时回调function-
onChange选中 option,或 input 的 value 变化时,调用此函数function(value, option:Option | Array<Option>)-
onClear清除内容时回调function-4.6.0
onDeselect取消选中时调用,参数为选中项的 value (或 key) 值,仅在 multipletags 模式下生效function(string | number | LabeledValue)-
onDropdownVisibleChange展开下拉菜单的回调function(open)-
onFocus获得焦点时回调function-
onInputKeyDown按键按下时回调function-
onMouseEnter鼠标移入时回调function-
onMouseLeave鼠标移出时回调function-
onPopupScroll下拉列表滚动时的回调function-
onSearch文本框值变化时回调function(value: string)-
onSelect被选中时调用,参数为选中项的 value (或 key) 值function(string | number | LabeledValue, option: Option)-

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

Select Methods

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

Option props

参数说明类型默认值版本
classNameOption 器类名string-
disabled是否禁用booleanfalse
title选中该 Option 后,Select 的 titlestring-
value默认根据此属性值进行筛选string | number-

OptGroup props

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

FAQ

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

看下 dropdownRender 例子 里的说明。

自定义 Option 样式导致滚动异常怎么办?

这是由于虚拟滚动默认选项高度为 32px,如果你的选项高度小于该值则需要通过 listItemHeight 属性调整,而 listHeight 用于设置滚动容器高度:

  1. <Select listItemHeight={10} listHeight={250} />

注意:listItemHeightlistHeight 为内部属性,如无必要,请勿修改该值。

为何无障碍测试会报缺失 aria- 属性?

Select 无障碍辅助元素仅在弹窗展开时创建,因而当你在进行无障碍检测时请先打开下拉后再进行测试。对于 aria-labelaria-labelledby 属性缺失警告,请自行为 Select 组件添加相应无障碍属性。