封装antd Input结合react-hook-form出现ref不存在的TS2769报错
报错核心原因
- 你封装的styled版本Input组件没有实现ref透传:当前你给styled传入的是普通箭头函数,没有用
React.forwardRef包裹,组件类型定义中根本没有暴露ref属性,TS自然会报“属性ref不存在”的错误,ref根本没法顺着组件链传到最底层的antd Input元素上。 - 类型定义冲突:你先后两次定义同名的
InputProps接口,后面自定义的接口完全覆盖了之前从antd导入的原生Input类型,导致组件的类型匹配逻辑完全失效。 - Controller用法不符合react-hook-form v7+的规范:当前用的
as属性、手动传ref={register()}的写法都是旧版本的废弃语法,新的类型定义已经移除了对这类写法的支持。
分步修复方案
修复styled组件的ref透传逻辑
先把传给styled的内部组件用forwardRef包裹,确保ref可以正确传递到antd原生Input上,同时删掉你样式代码里多写的闭合大括号:import styled from 'styled-components'; import AntInput from 'antd/es/input' import type { InputProps as AntdInputProps } from 'antd/es/input/Input'; import React from 'react'; // 先通过forwardRef把ref从外层组件接出来,透传给antd原生Input const BaseInput = React.forwardRef<HTMLInputElement, AntdInputProps>( (props, ref) => <AntInput {...props} ref={ref} /> ); // 再把透传能力正常的组件传给styled做样式封装 const Input = styled(BaseInput)` border: 1px solid #d7cce4; border-radius: 10px; background-color: #f5f2f8; &.ant-input { width: 100%; } .ant-input:placeholder-shown { text-overflow: ellipsis; } &:hover { border-color: #d7cce4; } `;清理自定义业务组件的类型定义
把自定义的业务props和antd的原生InputProps做区隔,不要重名导致类型覆盖:// 自定义业务props单独命名,避免和antd类型冲突 interface CustomInputFieldProps extends AntdInputProps { label?: React.ReactNode; name: string; customClassName?: string; required?: boolean; errors: Record<string, any>; } const InputField = React.forwardRef<HTMLInputElement, CustomInputFieldProps>( (props, ref) => { const { label, type = 'text', id, name, placeholder, customClassName = '', required = false, errors, ...restProps } = props; return ( <InputFieldWrapper> <FlexColumn> {label && <Label id={id || name} children={label} required={required} />} <Input {...restProps} type={type} placeholder={placeholder} id={id} ref={ref} /> {errors?.[name] && <Error>{errors[name]}</Error>} </FlexColumn> </InputFieldWrapper> ); } ); export default InputField;修正Controller的绑定逻辑
替换掉废弃的as属性和手动传ref的写法,用v7+官方推荐的renderprop完成表单绑定,不需要手动调用register:export default function Form() { const { control, errors, handleSubmit } = useForm({ resolver: yupResolver(schema), }); const formSubmit = (val: any) => { console.log("val", val); }; return ( <form onSubmit={handleSubmit(formSubmit)}> <Controller name="username" control={control} rules={{ required: true }} render={({ field }) => ( <InputField {...field} id="username" placeholder="Username" label="Username" required errors={errors} /> )} /> </form> ); }这里
field对象已经内置了react-hook-form需要的ref、value、onChange事件,直接透传给自定义InputField组件,就能正常完成表单值绑定、校验逻辑触发,不需要手动处理ref传递。
内容的提问来源于stack exchange,提问作者Serenity
相关产品推荐
相关产品推荐

