React+Antd 筛选搜索组件

343 阅读1分钟
import React, { useState } from 'react';
import { Popover, Button, Space } from 'antd';
import { FilterOutlined, CheckOutlined } from '@ant-design/icons';
import './index.less';

export default function SearchInput(props) {
  const { optionArr, setOptionArr, onSearch } = props;
  const [visible, setVisible] = useState(false);
  const [backgroundColor, setBackgroundColor] = useState('');
  const [checkColor, setCheckColor] = useState('white');

  const handleVisibleChange = visible => {
    setVisible(visible);
  };

  const handleOption = (item, index) => {
    const obj = Object.assign({}, item, { selected: !item.selected });
    let defaultArr = JSON.parse(JSON.stringify(optionArr));
    defaultArr.splice(index, 1, obj);
    setOptionArr(defaultArr);
  };

  const mouseEnter = index => {
    setBackgroundColor(index);
    setCheckColor('#F7F7F7');
  };

  const mouseLeave = index => {
    setBackgroundColor('');
    setCheckColor('white');
  };

  const handleOk = () => {
    onSearch();
    setVisible(false);  
  };

  return <div className="popoverClass">
    <Popover
      trigger="click"
      placement="bottom"
      visible={visible}
      onVisibleChange={handleVisibleChange}
      content={
        <div style={{ marginTop: -10 }}>
          {
            optionArr.map((item, index) => {
              return <div
                style={{ marginTop: 6, marginRight: 5, background: backgroundColor === index ? '#F7F7F7' : '' }}
                onClick={() => handleOption(item, index)}
                onMouseEnter={() => mouseEnter(index)}
                onMouseLeave={() => mouseLeave(index)}
              >
                <Space style={{ cursor: 'pointer' }}>
                  <div>{item.selected ? <CheckOutlined style={{ color: '#009FD4' }} /> : <CheckOutlined style={{ color: backgroundColor === index ? checkColor : 'white'  }} />}</div>
                  <div>{item.name}</div>
                </Space>
              </div>
            })
          }
          <div style={{ height: 1, background: '#EBEBEB', marginTop: 3, marginBottom: 8 }}></div>
          <Space>
            <Button onClick={()=>setVisible(false)}size="small" style={{ borderRadius: 4 }}>取消</Button>
            <Button onClick={handleOk} size="small" style={{ color: 'white', background: '#009FD4', borderColor: '#009FD4', borderRadius: 4 }}>确定</Button>
          </Space>
        </div>
      }
    >
      <Space>
        <FilterOutlined
          style={{ cursor: 'pointer', color: optionArr.filter(item => item.selected === true).length === 0 ? '' : '#009FD4'}}
        >
        </FilterOutlined>
        {
          optionArr.filter(item => item.selected === true).length === 0 ? null :
          <div style={{ marginLeft: -5, color: '#009FD4' }}>({optionArr.filter(item => item.selected === true).length})</div>
        }
      </Space>
    </Popover>
  </div>
};