[英]How can I set the props type in HOC in react-typescript?
我有一个简单的 withAuth HOC。 我正在尝试定义道具的类型。
const withAuth = (Component: typeof React.Component) => (role: string) => {
return (props) => {
const { data, loading } = useGetUser();
if (loading) {
return <p>Loading...</p>;
}
if (!data) {
return <Redirect ssr to="/api/v1/login" />;
} else {
if (role && !isAuthorized(data, role)) {
return <Redirect ssr to="/api/v1/login" />;
}
return <Component user={data} loading={loading} {...props} />;
}
};
};
我试过这个:
React.Component<T>
然后将T
传递给props:T
我收到 2 个警告。
Component: typeof React.Component<T> // Parameter '(Missing)' implicitly has an 'any' type.
props:T // Cannot find name 'T'
在这里你有:
import React, { FC } from 'react'
type Props = {
name: string
}
const A: FC<Props> = () => <div></div>
const withAuth = <P extends object>(Component: React.ComponentType<P>) => (role: string) => {
return (props: P) => {
return <Component {...props} />;
}
};
const result1 = withAuth(A)('hello')({ label: 'hello' }) // error
const result2 = withAuth(A)('hello')({ name: 'hello' }) // ok
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.