【发布时间】:2022-01-08 21:33:50
【问题描述】:
在我的 React (w/ typescript) 应用程序中,我使用 react-hook-form 创建了一个表单来管理它的所有逻辑。
然后我用一些 css 和其他东西自定义了 select 元素。但是,为了问题的简单起见,这里是准系统组件:
import { forwardRef } from 'react';
type Props = React.DetailedHTMLProps<React.InputHTMLAttributes<HTMLSelectElement>, HTMLSelectElement>;
const Select = forwardRef<HTMLSelectElement, Props>((props, ref) => {
return (
<select ref={ref} {...props}>
<option value="">...</option>
{props.children}
</select>
);
});
export default Select;
然后我定义了另一个“专门化”前一个组件的组件,如:
import { forwardRef } from 'react';
import Select from './select';
type Props = React.DetailedHTMLProps<React.InputHTMLAttributes<HTMLSelectElement>, HTMLSelectElement> & { label: string; errors?: string };
const SelectWitLargeData = forwardRef<HTMLSelectElement, Props>((props, ref) => {
return (
<Select ref={ref} {...props}>
...large amount of options
</Select>
);
});
export default SelectWitLargeData;
问题是编译器在
上给了我一个错误Type 'ForwardedRef<HTMLSelectElement> | LegacyRef<HTMLSelectElement>' is not assignable to type 'Ref<HTMLSelectElement>'.
Type 'string' is not assignable to type 'Ref<HTMLSelectElement>'.ts(2322)
index.d.ts(140, 9): The expected type comes from property 'ref' which is declared here on
type 'IntrinsicAttributes & Pick<Props, "label" | "key" | keyof InputHTMLAttributes<HTMLSelectElement> | "errors"> & RefAttributes<...>'
(JSX attribute) RefAttributes<HTMLSelectElement>.ref?: Ref<HTMLSelectElement>
我在网上搜索了解决方案,找到了很多建议,但这些都不起作用。
任何帮助表示赞赏 提前致谢!
编辑 这是使用组件的示例表单
import { useEffect } from 'react';
import { useForm } from 'react-hook-form';
import Select from '@components/select';
import SelectWithLargeData from '@components/select-with-large-data';
type Form = {
email: string;
state: string;
country: string;
};
const Address: React.FC = () => {
const { handleSubmit, register, setValue } = useForm<Form>();
useEffect(() => {
setValue('state', 'AL');
}, [setValue]);
const onSubmit = async (input: Form) => {
console.log(input);
};
return (
<>
<form onSubmit={handleSubmit(onSubmit)} className="space-y-10">
<input type="email" {...register('email', { required: true })} />
<SelectWithLargeData label="Provincia" {...register('state', { required: true })} />
<Select label="Stato" {...register('country', { required: true })}>
<option value="IT">Italia</option>
</Select>
</form>
</>
);
};
export default Address;
编辑 2 https://codesandbox.io/s/withered-rain-w9ej4
【问题讨论】:
标签: reactjs typescript react-hooks react-hook-form