Reactjs Can';t在Typescript中编写高阶组件:JSX元素类型没有任何构造或调用签名
是的,我知道有人问过这个问题,但我发现没有一个答案能解决这个问题。我正在用Typescript编写一个简单的高阶组件,以在呈现组件之前验证授权。目前看来是这样的:Reactjs Can';t在Typescript中编写高阶组件:JSX元素类型没有任何构造或调用签名,reactjs,typescript,higher-order-components,Reactjs,Typescript,Higher Order Components,是的,我知道有人问过这个问题,但我发现没有一个答案能解决这个问题。我正在用Typescript编写一个简单的高阶组件,以在呈现组件之前验证授权。目前看来是这样的: export function withAuth(Component: React.ComponentType) { if (!Component) return null; useEffect(() => { verifyToken().then(res => console.log(
export function withAuth(Component: React.ComponentType) {
if (!Component) return null;
useEffect(() => {
verifyToken().then(res => console.log(res))
}, []);
return (
<Component/>
)
}
使用auth导出函数(组件:React.ComponentType){
如果(!组件)返回空值;
useffect(()=>{
verifyToken().then(res=>console.log(res))
}, []);
返回(
)
}
我有一个更大的名为EditorContainer
的函数组件,我将它传递给HOC并从它自己的文件中导出:export default with auth(EditorContainer)
从“/modules/Editor/containers/EditorContainer”中导入为import EditorContainer
并抛出此错误
我试过:
react、react-dom、@types/react
和@types/react-dom
似乎不允许在TypeScript中编写高阶组件。通过将HOC定义为:
export const with auth=(组件:组件类型)=>(道具:任意)=>{
const AuthWrapper:FunctionComponent=(道具:any)=>{
const[auth,setAuth]=useState(null);
useffect(()=>{
验证令牌()。然后(res=>{
控制台日志(res);
setAuth(res);
})
}, []);
如果(!auth)返回;
返回(
)
}
返回;
};
我真的不知道为什么会这样,所以我想这个问题还没有真正得到答案。显式返回函数与返回函数组件有什么区别。。。是函数吗?特别是在剥离类型之后,我不清楚区别是什么。请参阅我的评论,了解您的解决方案为何有效;但是,您可以删除额外的功能
使用auth导出函数(组件:React.ComponentType){
if(Component==null){return()=>null;}
return()=>{
useffect(()=>{
verifyToken().then(res=>console.log(res))
}, []);
返回(
)
};
}
这是因为HOC的输入是一个组件,而输出需要是一个组件。现在可以这样做,因为您正在返回一个无状态函数,该函数正在返回一个钩子。:)。无状态函数是有效的react组件。感谢您的回复。也许我有点笨,但不管返回值是否是函数,它最终只是返回一个React元素。因此,如果我将HOC的返回类型设置为ReactElement,为什么它会接受一个匿名函数,它只返回一个元素,而不直接返回元素?HOC不会返回ReactElement。HOC需要返回一个组件类
或函数组件
。在您最初的帖子中,withAuth
不是HOC,它是一个返回React元素的FunctionType
withAuth(EditorContainer)
应返回一个ComponentType
,以使用来自导出默认withAuth(EditorContainer)
的react来满足合同。一旦添加了匿名函数作为withAuth
的返回类型,现在就有了一个有效的ComponentType
。匿名fn是一个有效的组件类型
,因为它返回一个ReactElement。我想我几乎能理解,但这并不是因为缺少答案。谢谢
export const withAuth = (Component: ComponentType<any>) => (props: any) => {
const AuthWrapper: FunctionComponent = (props: any) => {
const [auth, setAuth] = useState<any>(null);
useEffect(() => {
verifyToken().then(res => {
console.log(res);
setAuth(res);
})
}, []);
if (!auth) return <Result
status="403"
title="403"
subTitle="Sorry, you are not authorized to access this page."
extra={<Link to="/"><Button type="primary">Back Home</Button></Link>}
/>;
return (
<Component {...props} authUser={auth}/>
)
}
return <AuthWrapper {...props}/>;
};