首页 > 其他 > 详细

antd input with select

时间:2021-09-02 08:12:51      阅读:12      评论:0      收藏:0      [点我收藏+]

需求

用antd实现类似百度搜索框,带搜索的input文本输入框

分析

antd <Select> 有自带搜索的功能,但搜索后必须选择已有筛选项,不能自定义输入
技术分享图片
antd <Input> 没有发现有类似带搜索的功能(maybe没发现,如果有同学发现,请联系我,感谢)
可以使用: antd <AutoComplete>

实现

官方实现: <AutoComplete> filterOption

使用<AutoComplete>filterOption

antd <AutoComplete> 有自动带出option功能:
技术分享图片
官方代码:

import { AutoComplete } from ‘antd‘;

const options = [
  { value: ‘Burns Bay Road‘ },
  { value: ‘Downing Street‘ },
  { value: ‘Wall Street‘ },
];

const Complete: React.FC = () => (
  <AutoComplete
    style={{ width: 200 }}
    options={options}
    placeholder="try to type `b`"
    filterOption={(inputValue, option) =>
      option!.value.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1
    }
  />
);

ReactDOM.render(<Complete />, mountNode);

基于 <AutoComplete> onSearch 改写

对 <AutoComplete> 的onSearch事件进行了改写,根据输入值更新options

import React, { useState, useEffect } from ‘react‘;
import ReactDOM from ‘react-dom‘;
import ‘antd/dist/antd.css‘;
import ‘./index.css‘;
import { AutoComplete } from ‘antd‘;
const { Option } = AutoComplete;

const Complete = () => {
  const [result, setResult] = useState([]);
  const [sourceList, setSourceList] = useState([]);

  useEffect(() => {
    setSourceList([‘a‘, ‘aa‘, ‘aaa‘, ‘aaaa‘]);
  }, []);

  const handleSearch = value => {
    let res = [];
    value && sourceList.forEach(item => item.includes(value) && res.push(item));
    setResult(res);
  };

  return (
    <AutoComplete
      style={{width: 200}}
      onSearch={handleSearch}
      placeholder="input with select"
    >
      {result.map(item => (
        <Option key={item} value={item}>
          {item}
        </Option>
      ))}
    </AutoComplete>
  );
};

ReactDOM.render(<Complete />, document.getElementById(‘container‘));

StackBlitz代码地址:antd input with select
项目地址:(https://antd-input-with-select.stackblitz.io)

技术分享图片

antd input with select

原文:https://www.cnblogs.com/yanjiez/p/15206819.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!