Reactjs 通过';组件';与';通用';类型
我正在尝试使用泛型类型将组件作为道具传递。 但这不是一个简单的方法 我就是这么做的: 我创建了一个通过泛型类型获取道具的功能组件Reactjs 通过';组件';与';通用';类型,reactjs,typescript,Reactjs,Typescript,我正在尝试使用泛型类型将组件作为道具传递。 但这不是一个简单的方法 我就是这么做的: 我创建了一个通过泛型类型获取道具的功能组件 export interface CustomInputProps<Item> { itemKey?: keyof Item; } const CustomInput = <Item extends object>({ key, itemKey, name, defaultValue, ...props }: Prop
export interface CustomInputProps<Item> {
itemKey?: keyof Item;
}
const CustomInput = <Item extends object>({
key,
itemKey,
name,
defaultValue,
...props
}: PropsWithChildren<CustomInputProps<Item>>) => {
...
};
导出接口CustomInputProps{
itemKey?:项目的键;
}
常量自定义输入=({
钥匙
itemKey,
名称
默认值,
…道具
}:PropsWithChildren)=>{
...
};
我还创建了一个包装器组件,它将组件作为具有泛型类型的道具传递
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;
类型道具={
选中?:布尔值;
defaultValue?:字符串;
成分:T;
}&BaseInputProps和ExtractProps;
类型提取道具=
tComponentProps扩展了React.ComponentType
? TProps
:t组件道具;
常量InputWrapper:(p:Props)=>React.ReactElement=({
默认值,
选中的,
组成部分,
…道具,
}) => {
const[isChecked,setIsChecked]=使用状态(已检查);
返回(
{被检查了吗?
:
}
);
};
输出输入包装器;
我想通过道具传递组件,并通过泛型设置组件类型。(组件类型)
但是,我认为用“FC”包装组件类型并不是一个好主意
有更好的办法吗
<>
<InputWrapper<FC<CustomInputProps<Keys>>
key='key'
name={name}
defaultValue={defaultValues}
checked={isChecked}
Component={CustomInput}
{...props}
/>
</>