Reactjs 在泛型函数中使用React.ComponentProps
显然,使用Reactjs 在泛型函数中使用React.ComponentProps,reactjs,typescript,generics,Reactjs,Typescript,Generics,显然,使用React.ComponentProps是提取组件的正确方法 但是,属性类型无法在泛型函数中使用: function myFunction<T extends React.ComponentType<any>> (Component: React.ReactType, props: React.ComponentProps<T>) { // implementation } 样本组件: interface OwnProps { value
React.ComponentProps
是提取组件的正确方法
但是,属性类型无法在泛型函数中使用:
function myFunction<T extends React.ComponentType<any>>
(Component: React.ReactType, props: React.ComponentProps<T>) {
// implementation
}
样本组件:
interface OwnProps {
value: string;
}
const TestComponent: SFC<OwnProps> = (props) => {
const { } = props;
return (
<div />
);
};
如您所见,值
被分配了一个数值,但编译器没有检测到错误
一种方法是使用以下函数:
myFunction<typeof TestComponent>(TestComponent, {
value: 1
});
myFunction(TestComponent{
价值:1
});
它可以工作,但我很好奇,如果不使用typeof
函数myFunction,它是如何工作的
function myFunction<T extends React.ComponentType<any>>
(Component: React.ReactType, props: React.ComponentProps<T>) {
// implementation
}
(组件:React.ReactType,props:React.ComponentProps){
//实施
}
在此定义中,组件可以是任何React.ReactType。没有提到T,所以这不会强制组件和道具之间的任何关系
相反,我相信你想要这个:
function myFunction<T extends React.ComponentType<any>>
(Component: T, props: React.ComponentProps<T> {
// implementation
}
函数myFunction
(成分:T,道具:React.ComponentProps{
//实施
}
非常好,将React.reactype替换为T确实解决了问题。谢谢
function myFunction<T extends React.ComponentType<any>>
(Component: T, props: React.ComponentProps<T> {
// implementation
}