美文网首页
React-hook-form Demo之外——实际的用法

React-hook-form Demo之外——实际的用法

作者: 清水包哟 | 来源:发表于2021-12-02 11:01 被阅读0次

control的应用

在react-hook-form的API中,有着controluseControl两个接口。官方文档描述的太过于简陋,以至于并不能帮你解决什么问题。

实际上,control被用于复杂表单下的这些场景,如果你有以下场景的需求,看下去:

  • 自定义Input组件
  • 子区域抽成组件

出现这样的需求往往是由于html的原生组件不能满足我们的需求,而一些组件库的风格又比较固定,不太好改成符合我们自己的界面风格。和实际业务场景中的表单十分复杂,为了达到结构简化和复用等目的,我们需要将其中子区域抽成一个组件,但是又要在一个form内受useForm的控制。

所以,当需要将关联在一起的input组合成一个组件,我们一般会这么写:

// 示例只含control的用法,未写useForm的相关用法,参照官方文档即可
// yourFomComponent.tsx
const { register, setValue, getValues, control } = useForm<FormValue>();
<form>
    <ColorEditor name="color" defaultValue="#FFFFFFF" control={control}></ColorEditor>
</form>

// yourComponent.tsx
export const ColorEditor = (props: UseControllerProps) => {
    const { field, fieldState } = useController(props);

    return (
        <div>
            <input type="color" {...field}></input>
            <input type="text" {...field}></input>
        </div >
    );
};

可以看到,在使用的时候control由useForm创建,useForm将一系列框架的方法和事件打包在其中用于作为参数传入。name,defaultVlue,control是UseControllerProps定义的参数,然后通过useController将control解包出来成了field,它与外部的register()的返回值一致。

但是,你说都抽成组件了,还是和外面的用法一样,control只是过了一道手而已,我想自己在中间加入我的控制怎么办。这个时候官方文档就不会告诉你怎么写,所以我们举个两个复杂例子:

场景一:自定义参数,不使用control的参数定义
// 示例只含control的用法,不含useForm的相关用法,参照官方文档即可

// yourFomComponent.tsx
const { register, setValue, getValues, control } = useForm<FormValue>();
<form>
    <CheckBox id={yourId} defaultValue={yourValue} 
        name="yourPropertyName" text="选择我" control={control}>
    </CheckBox>
</form>

// yourComponent.tsx
type Props = {
    id: string,
    name: string,
    text: string,
    defaultValue: boolean,
    control: Control
};
export const CheckBox = (props: Props) => {
    const { field } = useController({
        name: props.name,
        control: props.control
    });

    return (
        <div>
            <input id={props.id} type="checkbox" checked={props.defaultValue} {...field}></input>
            <label htmlFor={props.id}>{props.text}</label>
        </div >
    );
};
场景二:自定义操作,不使用control的默认方法
// 示例只含control的用法,不含useForm的相关用法,参照官方文档即可

// yourFomComponent.tsx
const { register, setValue, getValues, control } = useForm<FormValue>();
<form>
    <Number name="yourNumber" control={control} defaultValue={number}></Number>
</form>

// yourComponent.tsx
export const Number = (props: UseControllerProps) => {
    const { field, fieldState } = useController(props);
    const [editorValue, setEditorValue] = React.useState(props.defaultValue);
    const [mouseButton, setMouseButton] = React.useState(0);

    // 观察外部有没有使用 setValues()设置当前值 
    {
        const watchValue = useWatch({
            control: props.control,
            name: props.name,
            defaultValue: props.defaultValue
        });

        React.useEffect(() => {
            // 当观察值改变时,设置当前的编辑状态,触发重新渲染
            setEditorValue(watchValue);
        }, [watchValue]);
    }

    const handleMouseDownUp = (e: React.MouseEvent<HTMLInputElement>) => etMouseButton(e.buttons);
    const handleMouseLeave = (e: React.MouseEvent<HTMLInputElement>) => {
        if (e.buttons == 1)  setMouseButton(0);
    }
    const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        // 当值改变时重设状态值,保持input可编辑
        setEditorValue(e.target.value);

        if (mouseButton == 1) 
            field.onChange(e);
        else 
            e.stopPropagation(); // 阻止keyDown冒泡
    };

    const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
        if (e.key === "Enter")
            field.onChange(e);
    }

    return <input type="number" name={field.name}
        value={editorValue} ref={field.ref}
        onBlur={field.onBlur}
        onChange={handleChange}
        onKeyDown={handleKeyDown}
        onMouseDown={handleMouseDownUp}
        onMouseUp={handleMouseDownUp}
        onMouseLeave={handleMouseLeave}
    ></input>;
};

这个例子就复杂很多,它是一个数字的编辑器,在输入后按回车和点击上下箭头调整数字时触发change事件。
要实现这个就解决三个问题,

1. 内部事件的拦截

拦截input的onChange事件,在其中判断用户时鼠标点击还是在键盘输入。同时,处理onKeyDown事件,在用户按下回车时,触发change。

2. 使控件可编辑

我们知道input控件实现值编辑就是通过onChange事件改变状态后重新render实现的,但是在这个场景下,我们拦截了onChange事件,这样input就处于不可编辑的状态。所以添加一个内部状态editorValue作为编辑值,在onChange事件中修改状态,保证input可编辑。

3. 使控件响应setValue()

当前编辑值改为内部状态后,我们就和form中的值失去了联系了。除了从defaultValue传入的初始值之外,外部setValue()当前name的时候,控件就不会有任何响应。我们通过useWatch来监视当前name来,当外部setValue时,我们收到消息,改变input控件的状态值。

相关文章

网友评论

      本文标题:React-hook-form Demo之外——实际的用法

      本文链接:https://www.haomeiwen.com/subject/avryxrtx.html