我正在尝试将组件作为具有通用类型的prop传递。 但这不是简单的方法。
这就是我要做的:
我创建了一个通过通用类型获取道具的功能组件。
export interface CustomInputProps<Item> {
itemKey?: keyof Item;
}
const CustomInput = <Item extends object>({
key,
itemKey,
name,
defaultValue,
...props
}: PropsWithChildren<CustomInputProps<Item>>) => {
...
};
我还创建了一个包装器组件,该组件将组件作为具有通用类型的道具传递。
type Props<T> = {
checked?: boolean;
defaultValue?: string;
Component: T;
} & BaseInputProps & ExtractProps<T>;
type ExtractProps<TComponentOrTProps> =
TComponentOrTProps extends React.ComponentType<infer TProps>
? TProps
: TComponentOrTProps;
const InputWrapper: <T extends React.FC<any>>(p: Props<T>) => React.ReactElement<Props<T>> = ({
defaultValue,
checked,
Component,
...props,
}) => {
const [isChecked, setIsChecked] = useState(checked);
return (
<>
{isChecked ?
<Input
defaultValue={defaultValue}
/>
:
<Component
defaultValue={defaultValue}
{...props}
>
}
</>
);
};
export InputWrapper;
我想通过props传递组件,并通过泛型设置组件类型。 (组件类型)
但是,我认为通过用'FC'包装组件类型来发送消息不是一个好主意。
有更好的方法吗?
<>
<InputWrapper<FC<CustomInputProps<Keys>>
key='key'
name={name}
defaultValue={defaultValues}
checked={isChecked}
Component={CustomInput}
{...props}
/>
</>