如何在不使用forwardRef的情况下以react hook形式实现组合组件?

问题描述 投票:0回答:1

forwardRef 的工作示例: https://codesandbox.io/p/sandbox/musing-lake-x545nm

我有一个使用 forwardRef 的工作示例,但它在

React 19
中已被弃用,并且将来会被删除。为了避免返工,我删除了 forwardRefs。但如果我删除它。我收到以下错误。

Warning: Function components cannot be given refs. 
Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

复选框.tsx

import { forwardRef } from "react";

export default forwardRef<HTMLInputElement>(function CheckBox(
  { name, ...props },
  ref
) {
  return (
    <input
      name={name}
      ref={ref}
      type="checkbox"
      autoComplete="off"
      {...props}
    />
  );
});

Field.tsx

当我使用

<Field type="checkbox" />
时,它将动态渲染复选框字段。

import { useFormContext } from "react-hook-form";
import Checkbox from "./Checkbox";

const Fields = {
  checkbox: Checkbox,
};

export default function Field({ name, label, type, ...props }) {
  const { register } = useFormContext();
  const Component = Fields[type];
  return (
    <>
      <Component {...register(name)} {...props} />
      <label>{label}</label>
    </>
  );
}

App.tsx

import Field from "./Field";
import { FormProvider, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";

const schema = z.object({
  terms: z.boolean(),
});

type DataTypes = z.infer<typeof schema>;

export default function App() {
  const instance = useForm<DataTypes>({
    resolver: zodResolver(schema),
  });
  const { handleSubmit } = instance;

  return (
    <div className="App">
      <FormProvider<DataTypes> {...instance}>
        <form onSubmit={handleSubmit((data) => console.log(data))}>
          <Field name="terms" type="checkbox" label="Accept Terms" />
          <br />
          <button type="submit">Submit</button>
        </form>
      </FormProvider>
    </div>
  );
}

我尝试使用 useRef,但遇到了同样的错误。

reactjs react-hook-form react-forwardref
1个回答
0
投票

找到解决办法 https://codesandbox.io/p/sandbox/festive-davinci-knwn5r

必须解构react hook形式的register函数,分别传递ref和props

 const { ref, ...inputProps } = register(name);

 <Component inputRef={ref} {...inputProps} {...props} />
© www.soinside.com 2019 - 2024. All rights reserved.