Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, {useState} from 'react'
- import produce from 'immer'
- const filterField=(value)=>(item)=>{
- return item.name?.includes(value)
- }
- function useShutterForm({fields=[], filterFunc=filterField}){
- const [values, setValues] = useState({
- leftFields: fields.map((item, index)=>({...item, checked: false, index})),
- rightFields: [],
- leftKeyword: '',
- rightKeyword: '',
- })
- const leftFields = values.leftFields
- const rightFields = values.rightFields
- const leftKeyword = values.leftKeyword
- const rightKeyword = values.rightKeyword
- const filteredLFields = values.leftFields.filter(filterFunc(values.leftKeyword))
- const filteredRFields = values.rightFields.filter(filterFunc(values.rightKeyword))
- const reset=()=>{
- setValues(produce(preState=>{
- preState.leftFields = fields.map(item=>({...item, checked: false}))
- preState.rightFields = []
- }))
- }
- const handleLKeywordChange = ({target: {value}})=>{
- setValues(produce(preState=>preState.leftKeyword = value))
- }
- const handleRKeywordChange = ({target: {value}})=>{
- setValues(produce(preState=>preState.rightKeyword = value))
- }
- const toggleLField = (index)=>()=>{
- setValues(produce(preState=> {
- preState.leftFields[index].checked = !values.leftFields[index].checked
- }))
- }
- const toggleLFields = ()=>{
- // not implemented
- }
- const transferL2R = ()=>{
- setValues(produce(preState=>{
- const toRFields = values.leftFields.filter(item=>item.checked)
- preState.leftFields = values.leftFields.filter(item=>!item.checked)
- preState.rightFields = [...values.rightFields, ...toRFields]
- }))
- }
- return {
- leftFields,
- rightFields,
- leftKeyword,
- rightKeyword,
- filteredLFields,
- filteredRFields,
- setValues,
- reset,
- transferL2R,
- toggleLField,
- handleLKeywordChange,
- handleRKeywordChange,
- }
- }
- const fields = [
- {name: '产品中文名称', field: 'cn_name'},
- {name: '产品英文名称', field: 'en_name'},
- ]
- function ShutterForm(){
- const form = useShutterForm({fields})
- return (
- <div>
- <div className={'leftPanel'}>
- <div>
- <input value={form.leftKeyword} onChange={form.handleLKeywordChange}/>
- </div>
- <div>
- {form.filteredLFields.map((item)=>(
- <div key={item.index}>
- <checkbox checked={item.checked} onChange={form.toggleLField(item.index)}/>
- <input id={item.index} name={item.field}/>
- </div>
- ))}
- </div>
- </div>
- <div className={'rightPanel'}>
- <div>
- <input value={form.rightKeyword} onChange={form.handleRKeywordChange}/>
- </div>
- <div>
- </div>
- </div>
- </div>
- )
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement