AutoComplete自动完成

输入框自动完成功能。

何时使用

需要自动完成时。

代码演示

AutoComplete自动完成 - 图1

基本使用

基本使用。通过 dataSource 设置自动完成的数据源

  1. import { AutoComplete } from 'antd';
  2. function onSelect(value) {
  3. console.log('onSelect', value);
  4. }
  5. class Complete extends React.Component {
  6. state = {
  7. dataSource: [],
  8. };
  9. handleSearch = value => {
  10. this.setState({
  11. dataSource: !value ? [] : [value, value + value, value + value + value],
  12. });
  13. };
  14. render() {
  15. const { dataSource } = this.state;
  16. return (
  17. <AutoComplete
  18. dataSource={dataSource}
  19. style={{ width: 200 }}
  20. onSelect={onSelect}
  21. onSearch={this.handleSearch}
  22. placeholder="input here"
  23. />
  24. );
  25. }
  26. }
  27. ReactDOM.render(<Complete />, mountNode);

AutoComplete自动完成 - 图2

自定义输入组件

自定义输入组件。

  1. import { AutoComplete, Input } from 'antd';
  2. const { TextArea } = Input;
  3. function onSelect(value) {
  4. console.log('onSelect', value);
  5. }
  6. class Complete extends React.Component {
  7. state = {
  8. dataSource: [],
  9. };
  10. handleSearch = value => {
  11. this.setState({
  12. dataSource: !value ? [] : [value, value + value, value + value + value],
  13. });
  14. };
  15. handleKeyPress = ev => {
  16. console.log('handleKeyPress', ev);
  17. };
  18. render() {
  19. const { dataSource } = this.state;
  20. return (
  21. <AutoComplete
  22. dataSource={dataSource}
  23. style={{ width: 200 }}
  24. onSelect={onSelect}
  25. onSearch={this.handleSearch}
  26. >
  27. <TextArea
  28. placeholder="input here"
  29. className="custom"
  30. style={{ height: 50 }}
  31. onKeyPress={this.handleKeyPress}
  32. />
  33. </AutoComplete>
  34. );
  35. }
  36. }
  37. ReactDOM.render(<Complete />, mountNode);

AutoComplete自动完成 - 图3

查询模式 - 确定类目

查询模式: 确定类目 示例。

  1. import { Icon, Input, AutoComplete } from 'antd';
  2. const { Option, OptGroup } = AutoComplete;
  3. const dataSource = [
  4. {
  5. title: 'Libraries',
  6. children: [
  7. {
  8. title: 'AntDesign',
  9. count: 10000,
  10. },
  11. {
  12. title: 'AntDesign UI',
  13. count: 10600,
  14. },
  15. ],
  16. },
  17. {
  18. title: 'Solutions',
  19. children: [
  20. {
  21. title: 'AntDesign UI',
  22. count: 60100,
  23. },
  24. {
  25. title: 'AntDesign',
  26. count: 30010,
  27. },
  28. ],
  29. },
  30. {
  31. title: 'Articles',
  32. children: [
  33. {
  34. title: 'AntDesign design language',
  35. count: 100000,
  36. },
  37. ],
  38. },
  39. ];
  40. function renderTitle(title) {
  41. return (
  42. <span>
  43. {title}
  44. <a
  45. style={{ float: 'right' }}
  46. href="https://www.google.com/search?q=antd"
  47. target="_blank"
  48. rel="noopener noreferrer"
  49. >
  50. more
  51. </a>
  52. </span>
  53. );
  54. }
  55. const options = dataSource
  56. .map(group => (
  57. <OptGroup key={group.title} label={renderTitle(group.title)}>
  58. {group.children.map(opt => (
  59. <Option key={opt.title} value={opt.title}>
  60. {opt.title}
  61. <span className="certain-search-item-count">{opt.count} people</span>
  62. </Option>
  63. ))}
  64. </OptGroup>
  65. ))
  66. .concat([
  67. <Option disabled key="all" className="show-all">
  68. <a href="https://www.google.com/search?q=antd" target="_blank" rel="noopener noreferrer">
  69. View all results
  70. </a>
  71. </Option>,
  72. ]);
  73. function Complete() {
  74. return (
  75. <div className="certain-category-search-wrapper" style={{ width: 250 }}>
  76. <AutoComplete
  77. className="certain-category-search"
  78. dropdownClassName="certain-category-search-dropdown"
  79. dropdownMatchSelectWidth={false}
  80. dropdownStyle={{ width: 300 }}
  81. size="large"
  82. style={{ width: '100%' }}
  83. dataSource={options}
  84. placeholder="input here"
  85. optionLabelProp="value"
  86. >
  87. <Input suffix={<Icon type="search" className="certain-category-icon" />} />
  88. </AutoComplete>
  89. </div>
  90. );
  91. }
  92. ReactDOM.render(<Complete />, mountNode);
  1. .certain-category-search.ant-select-auto-complete .ant-input-affix-wrapper .ant-input-suffix {
  2. right: 12px;
  3. }
  4. .certain-category-search-dropdown .ant-select-dropdown-menu-item-group-title {
  5. color: #666;
  6. font-weight: bold;
  7. }
  8. .certain-category-search-dropdown .ant-select-dropdown-menu-item-group {
  9. border-bottom: 1px solid #f6f6f6;
  10. }
  11. .certain-category-search-dropdown .ant-select-dropdown-menu-item {
  12. padding-left: 16px;
  13. }
  14. .certain-category-search-dropdown .ant-select-dropdown-menu-item.show-all {
  15. text-align: center;
  16. cursor: default;
  17. }
  18. .certain-category-search-dropdown .ant-select-dropdown-menu {
  19. max-height: 300px;
  20. }
  21. .certain-search-item-count {
  22. position: absolute;
  23. color: #999;
  24. right: 16px;
  25. }
  26. .certain-category-search.ant-select-focused .certain-category-icon {
  27. color: #108ee9;
  28. }
  29. .certain-category-icon {
  30. color: #6e6e6e;
  31. transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
  32. font-size: 16px;
  33. }

AutoComplete自动完成 - 图4

自定义选项

也可以直接传 AutoComplete.Option 作为 AutoCompletechildren,而非使用 dataSource

  1. import { AutoComplete } from 'antd';
  2. const { Option } = AutoComplete;
  3. class Complete extends React.Component {
  4. state = {
  5. result: [],
  6. };
  7. handleSearch = value => {
  8. let result;
  9. if (!value || value.indexOf('@') >= 0) {
  10. result = [];
  11. } else {
  12. result = ['gmail.com', '163.com', 'qq.com'].map(domain => `${value}@${domain}`);
  13. }
  14. this.setState({ result });
  15. };
  16. render() {
  17. const { result } = this.state;
  18. const children = result.map(email => <Option key={email}>{email}</Option>);
  19. return (
  20. <AutoComplete style={{ width: 200 }} onSearch={this.handleSearch} placeholder="input here">
  21. {children}
  22. </AutoComplete>
  23. );
  24. }
  25. }
  26. ReactDOM.render(<Complete />, mountNode);

AutoComplete自动完成 - 图5

不区分大小写

不区分大小写的 AutoComplete

  1. import { AutoComplete } from 'antd';
  2. const dataSource = ['Burns Bay Road', 'Downing Street', 'Wall Street'];
  3. function Complete() {
  4. return (
  5. <AutoComplete
  6. style={{ width: 200 }}
  7. dataSource={dataSource}
  8. placeholder="try to type `b`"
  9. filterOption={(inputValue, option) =>
  10. option.props.children.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1
  11. }
  12. />
  13. );
  14. }
  15. ReactDOM.render(<Complete />, mountNode);

AutoComplete自动完成 - 图6

查询模式 - 不确定类目

查询模式: 不确定类目 示例。

  1. import { Icon, Button, Input, AutoComplete } from 'antd';
  2. const { Option } = AutoComplete;
  3. function onSelect(value) {
  4. console.log('onSelect', value);
  5. }
  6. function getRandomInt(max, min = 0) {
  7. return Math.floor(Math.random() * (max - min + 1)) + min; // eslint-disable-line no-mixed-operators
  8. }
  9. function searchResult(query) {
  10. return new Array(getRandomInt(5))
  11. .join('.')
  12. .split('.')
  13. .map((item, idx) => ({
  14. query,
  15. category: `${query}${idx}`,
  16. count: getRandomInt(200, 100),
  17. }));
  18. }
  19. function renderOption(item) {
  20. return (
  21. <Option key={item.category} text={item.category}>
  22. <div className="global-search-item">
  23. <span className="global-search-item-desc">
  24. Found {item.query} on
  25. <a
  26. href={`https://s.taobao.com/search?q=${item.query}`}
  27. target="_blank"
  28. rel="noopener noreferrer"
  29. >
  30. {item.category}
  31. </a>
  32. </span>
  33. <span className="global-search-item-count">{item.count} results</span>
  34. </div>
  35. </Option>
  36. );
  37. }
  38. class Complete extends React.Component {
  39. state = {
  40. dataSource: [],
  41. };
  42. handleSearch = value => {
  43. this.setState({
  44. dataSource: value ? searchResult(value) : [],
  45. });
  46. };
  47. render() {
  48. const { dataSource } = this.state;
  49. return (
  50. <div className="global-search-wrapper" style={{ width: 300 }}>
  51. <AutoComplete
  52. className="global-search"
  53. size="large"
  54. style={{ width: '100%' }}
  55. dataSource={dataSource.map(renderOption)}
  56. onSelect={onSelect}
  57. onSearch={this.handleSearch}
  58. placeholder="input here"
  59. optionLabelProp="text"
  60. >
  61. <Input
  62. suffix={
  63. <Button
  64. className="search-btn"
  65. style={{ marginRight: -12 }}
  66. size="large"
  67. type="primary"
  68. >
  69. <Icon type="search" />
  70. </Button>
  71. }
  72. />
  73. </AutoComplete>
  74. </div>
  75. );
  76. }
  77. }
  78. ReactDOM.render(<Complete />, mountNode);
  1. .global-search-wrapper {
  2. padding-right: 50px;
  3. }
  4. .global-search {
  5. width: 100%;
  6. }
  7. .global-search.ant-select-auto-complete .ant-select-selection--single {
  8. margin-right: -46px;
  9. }
  10. .global-search.ant-select-auto-complete .ant-input-affix-wrapper .ant-input:not(:last-child) {
  11. padding-right: 62px;
  12. }
  13. .global-search.ant-select-auto-complete .ant-input-affix-wrapper .ant-input-suffix button {
  14. border-top-left-radius: 0;
  15. border-bottom-left-radius: 0;
  16. }
  17. .global-search-item {
  18. display: flex;
  19. }
  20. .global-search-item-desc {
  21. flex: auto;
  22. text-overflow: ellipsis;
  23. overflow: hidden;
  24. }
  25. .global-search-item-count {
  26. flex: none;
  27. }

API

  1. const dataSource = ['12345', '23456', '34567'];
  2. <AutoComplete dataSource={dataSource} />;
参数说明类型默认值
allowClear支持清除, 单选模式有效booleanfalse
autoFocus自动获取焦点booleanfalse
backfill使用键盘选择选项的时候把选中项回填到输入框中booleanfalse
children (自动完成的数据源)自动完成的数据源React.ReactElement / Array<React.ReactElement>-
children (自定义输入框)自定义输入框HTMLInputElement / HTMLTextAreaElement / React.ReactElement<Input />
dataSource自动完成的数据源DataSourceItemType[]
defaultActiveFirstOption是否默认高亮第一个选项。booleantrue
defaultValue指定默认选中的条目string|string[]| 无
disabled是否禁用booleanfalse
filterOption是否根据输入项进行筛选。当其为一个函数时,会接收 inputValue option 两个参数,当 option 符合筛选条件时,应返回 true,反之则返回 falseboolean or function(inputValue, option)true
getPopupContainer菜单渲染父节点。默认渲染到 body 上,如果你遇到菜单滚动定位问题,试试修改为滚动的区域,并相对其定位。示例Function(triggerNode)() => document.body
optionLabelProp回填到选择框的 Option 的属性值,默认是 Option 的子元素。比如在子元素需要高亮效果时,此值可以设为 valuestringchildren
placeholder输入框提示string-
value指定当前选中的条目string|string[]|{ key: string, label: string|ReactNode }|Array<{ key: string, label: string|ReactNode }>
onBlur失去焦点时的回调function()-
onChange选中 option,或 input 的 value 变化时,调用此函数function(value)
onFocus获得焦点时的回调function()-
onSearch搜索补全项的时候调用function(value)
onSelect被选中时调用,参数为选中项的 value 值function(value, option)
defaultOpen是否默认展开下拉菜单boolean-
open是否展开下拉菜单boolean-
onDropdownVisibleChange展开下拉菜单的回调function(open)-

方法

名称描述
blur()移除焦点
focus()获取焦点