目录
- react使用hook封装一个search+input+checkbox组件
-
react使用hook封装一个search+input+checkbox组件
searchPro.jsx
import { Checkbox, Input } from "antd";
import React, { useEffect, useState } from "react";
import Styled from "styled-components";
const { Search } = Input;
const proDataAll = [{ name:'项目1', value:'1',check:false},{ name:'项目2', value:'2',check:false},{ name:'项目3', value:'3',check:false},{ name:'管理1', value:'11',check:false},{ name:'管理2', value:'12',check:false},{ name:'管理3', value:'13',check:false},{ name:'业务1', value:'111',check:false},{ name:'业务2', value:'业务112',check:false},{ name:'业务3', value:'113',check:false},{ name:'测试', value:'01',check:false},{ name:'测试1', value:'02',check:false},{ name:'测试2', value:'03',check:false},
]
export default function SearchPro(props) {const [proData, setProData ] = useState([])const [selectData, setSelectData ] = useState([])useEffect(()=>{setProData(proDataAll)},[])const onSearch = (value) => {let resSelect = []if ( value ) {resSelect = proData && proData.length ? proData.filter(item => {if ( item.name.indexOf(value) > -1 || value === item.name ) {return item}}) : []} else {resSelect = [...proDataAll]}console.log('onSearch-resSelect',resSelect);setProData(resSelect)}const onChange = ( e, item ) => {let resSelect = [] let resProData = [] if ( e.target.checked ) {resSelect = [...selectData,{...item, check:true }];resProData = proData && proData.length ? proData.map(it => {if ( it.value === item.value ) {it.check = true}return it}) : [];} else {resSelect = selectData && selectData.length ? selectData.filter(it => {if ( !e.target.checked && it.value !== item.value ) {return it}}) : [...selectData];resProData = proData && proData.length ? proData.map(it => {if ( it.value === item.value ) {it.check = false}return it}) : [];}setSelectData(resSelect)setProData(resProData)}return (<SearchProWrap><Searchplaceholder="请输入"onSearch={onSearch}allowClearstyle={{width: 200,}}/><div className='mian'><div className='main-left'>{proData && proData.length ? proData.map(item => {return (<div className='main-left-item' key={item.value}><div>{item.name}</div><div><Checkbox onChange={(event) => onChange(event,item)} checked={item.check}>{}</Checkbox></div></div>)}) : ''}</div><div className='main-right'>{selectData && selectData.length ? selectData.map(item=>{return (<div key={item.value}>{ item && item.name ? item.name : '' }</div>)}) : ''}</div></div></SearchProWrap>);
}const SearchProWrap = Styled.div`color: #000;.mian {display: flex;width: 650px;margin-top: 20px;.main-left {width:400px;background: #eee;margin-right: 20px;.main-left-item {display: flex;justify-content: space-between;padding: 4px 10px;margin-bottom: 10px;}}.main-right {width: 200px;background: #eee}}
`;
使用组件
import React from 'react';
import SearchPro from "./SearchPro";
export default function app(props) {return (<div><SearchPro /></div>)
}
效果