react18中使用react-hook-form

目录

  • 用法
  • 小问题

用法

import { useForm, useFieldArray, useController} from "react-hook-form"

const FWHFTest= () => {
	const { control, register, handleSubmit, getValues, errors, reset, setValue } = useForm({
	    defaultValues: {
	        rules: [
	            {
	                name: "",
				    state: false
	            },
	        ],
	    },
	})
    const { fields, append, remove, prepend } = useFieldArray({
        control,
        name: "rules",
    })
    // 获取数据
    const get() => {
    	let forms = getValues().rules
    }
    // 添加数据
    const addRules = () => {
        setValue("rules", [
            ...(getValues().rules || []),
            {
                name: "",
				state: false
            }
        ])
    }
    
    // 绑定到dom
    const Item = ({ item, index, control }) => {
        return (
            <div key={item?.id || index}>
                <TextField variant="outlined" size={"small"} {...register(`rules[${index}].name`)} />
                <TextField variant="outlined" size={"small"} {...register(`rules[${index}].state`)} />
                <div className={"active"}>
                	<span onClick={() => remove(index)}>删除</span>
                </div>
            </div>
        )
    }
    return <div>
		{fields?.map((item, index) => {
	    	<Item item={item} index={index} key={index} control={control}/>
	    })}
	</div>
}
export default FWHFTest

小问题

如上第三方ui库TextField,它的绑定值是value。当使用Checkbox、Switch等插件绑定值是checked的时候继续使用{…register(rules[${index}].state)}将导致UI库插件无法正确显示值为true时的状态。
解决办法(使用useController、control ):

const Item = ({ item, index, control }) => {
	const { field } = useController({
        name: `rules[${index}].state`,
        control: control
    });
    return (
        <div key={item?.id || index}>
            <TextField variant="outlined" size={"small"} {...register(`rules[${index}].name`)} />
            <Switch
                size={"small"}
                checked={field.value}
                {...field}
            />
            <div className={"active"}>
            	<span onClick={() => remove(index)}>删除</span>
            </div>
        </div>
    )
}

你可能感兴趣的:(react,react.js,javascript,前端)