是否在业务中写很多的符合业务的搜索组件。但是其根本就是换个请求的 API 或者是 使用的获取字段,也或者是进行搜索的字段名称不一致。
react hook 其实很大的好处是把原来的无状态组件,用hook 这一特性勾入需要的状态值。这样在我们组件开发的时候带来的很多的便利性。
下面我们看下如何去实现这个组件。先上代码:
import React, { useState, useEffect } from 'react';
import { Popover, Input, Button, Space } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import './index.less';
export default function SearchInput(props) {
const [visible, setVisible] = useState(false);
const [inputValue, setInputValue] = useState('');
const handleVisibleChange = visible => {
setVisible(visible);
};
const handleSearch = () => {
props.onSearch(inputValue.trim());
setVisible(false);
};
const inputChange = e => {
setInputValue(e.target.value);
};
const handleEnterSearch = e => {
if( e.nativeEvent.keyCode === 13 ){
handleSearch();
}
}
return <div className="popoverClass">
<Popover
trigger="click"
placement="bottom"
visible={visible}
onVisibleChange={handleVisibleChange}
content={
<Space>
<Input
className="inputClass"
onChange={inputChange}
onKeyPress={handleEnterSearch}
/>
<Button
style={{ color: 'white', background: '#009FD4', borderColor: '#009FD4', borderRadius: 4 }}
onClick={handleSearch}
>
搜索
</Button>
</Space>
}
>
<SearchOutlined className={visible ? "isSelect" : "noSelect"}>搜索</SearchOutlined>
</Popover>
</div>
};
上面搜索组件去空、回车搜索功能,搞定 90% 已上的搜索组件哪里能有。要用的即可直接复制。