问题
I have a simple withAuth HOC. I am trying to define the type for props.
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} />;
}
};
};
I tried this:
React.Component<T>
Then passing the T
to props:T
i am getting 2 warnings.
Component: typeof React.Component<T> // Parameter '(Missing)' implicitly has an 'any' type.
props:T // Cannot find name 'T'
回答1:
Here you have:
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
来源:https://stackoverflow.com/questions/65414467/how-can-i-set-the-props-type-in-hoc-in-react-typescript