• AutoComplete自动完成
    • 何时使用
    • 代码演示
    • API
    • 方法

    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 = AutoComplete.Option;
    3. const OptGroup = AutoComplete.OptGroup;
    4. const dataSource = [
    5. {
    6. title: '话题',
    7. children: [
    8. {
    9. title: 'AntDesign',
    10. count: 10000,
    11. },
    12. {
    13. title: 'AntDesign UI',
    14. count: 10600,
    15. },
    16. ],
    17. },
    18. {
    19. title: '问题',
    20. children: [
    21. {
    22. title: 'AntDesign UI 有多好',
    23. count: 60100,
    24. },
    25. {
    26. title: 'AntDesign 是啥',
    27. count: 30010,
    28. },
    29. ],
    30. },
    31. {
    32. title: '文章',
    33. children: [
    34. {
    35. title: 'AntDesign 是一个设计语言',
    36. count: 100000,
    37. },
    38. ],
    39. },
    40. ];
    41. function renderTitle(title) {
    42. return (
    43. <span>
    44. {title}
    45. <a
    46. style={{ float: 'right' }}
    47. href="https://www.google.com/search?q=antd"
    48. target="_blank"
    49. rel="noopener noreferrer"
    50. >
    51. 更多
    52. </a>
    53. </span>
    54. );
    55. }
    56. const options = dataSource
    57. .map(group => (
    58. <OptGroup key={group.title} label={renderTitle(group.title)}>
    59. {group.children.map(opt => (
    60. <Option key={opt.title} value={opt.title}>
    61. {opt.title}
    62. <span className="certain-search-item-count">{opt.count} 关注</span>
    63. </Option>
    64. ))}
    65. </OptGroup>
    66. ))
    67. .concat([
    68. <Option disabled key="all" className="show-all">
    69. <a href="https://www.google.com/search?q=antd" target="_blank" rel="noopener noreferrer">
    70. 查看所有结果
    71. </a>
    72. </Option>,
    73. ]);
    74. function Complete() {
    75. return (
    76. <div className="certain-category-search-wrapper" style={{ width: 250 }}>
    77. <AutoComplete
    78. className="certain-category-search"
    79. dropdownClassName="certain-category-search-dropdown"
    80. dropdownMatchSelectWidth={false}
    81. dropdownStyle={{ width: 300 }}
    82. size="large"
    83. style={{ width: '100%' }}
    84. dataSource={options}
    85. placeholder="input here"
    86. optionLabelProp="value"
    87. >
    88. <Input suffix={<Icon type="search" className="certain-category-icon" />} />
    89. </AutoComplete>
    90. </div>
    91. );
    92. }
    93. 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.Option;
    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.Option;
    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. {item.query}
    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. 区块中
    33. </span>
    34. <span className="global-search-item-count">约 {item.count} 个结果</span>
    35. </div>
    36. </Option>
    37. );
    38. }
    39. class Complete extends React.Component {
    40. state = {
    41. dataSource: [],
    42. };
    43. handleSearch = value => {
    44. this.setState({
    45. dataSource: value ? searchResult(value) : [],
    46. });
    47. };
    48. render() {
    49. const { dataSource } = this.state;
    50. return (
    51. <div className="global-search-wrapper" style={{ width: 300 }}>
    52. <AutoComplete
    53. className="global-search"
    54. size="large"
    55. style={{ width: '100%' }}
    56. dataSource={dataSource.map(renderOption)}
    57. onSelect={onSelect}
    58. onSearch={this.handleSearch}
    59. placeholder="input here"
    60. optionLabelProp="text"
    61. >
    62. <Input
    63. suffix={
    64. <Button className="search-btn" size="large" type="primary">
    65. <Icon type="search" />
    66. </Button>
    67. }
    68. />
    69. </AutoComplete>
    70. </div>
    71. );
    72. }
    73. }
    74. 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 {
    14. right: 0;
    15. }
    16. .global-search.ant-select-auto-complete .ant-input-affix-wrapper .ant-input-suffix button {
    17. border-top-left-radius: 0;
    18. border-bottom-left-radius: 0;
    19. }
    20. .global-search-item {
    21. display: flex;
    22. }
    23. .global-search-item-desc {
    24. flex: auto;
    25. text-overflow: ellipsis;
    26. overflow: hidden;
    27. }
    28. .global-search-item-count {
    29. flex: none;
    30. }

    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
    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()获取焦点