Reactjs React-Typescript-绑定元素“C”隐式具有“any”类型。TS7031
关于react组件,我在将js转换为ts格式时遇到问题 错误是 绑定元素“C”隐式具有“any”类型。TS7031 它发生在该函数的参数C上:Reactjs React-Typescript-绑定元素“C”隐式具有“any”类型。TS7031,reactjs,typescript,Reactjs,Typescript,关于react组件,我在将js转换为ts格式时遇到问题 错误是 绑定元素“C”隐式具有“any”类型。TS7031 它发生在该函数的参数C上: export default function UnauthenticatedRoute({ component: C, appProps, ...rest }: RouteProps & {appProps: AppProps}) { cons
export default function UnauthenticatedRoute({ component: C, appProps, ...rest }:
RouteProps & {appProps: AppProps}) {
const redirect = querystring("redirect");
return (
<Route {...rest}
render={ props => !appProps.isAuthenticated ?
<C {...props} {...appProps} />
:
<Redirect to={redirect === "" || redirect === null ? "/" : redirect}/>
}
/>
);
}
据我所知,RouteProps中的组件键如下所示:
组件?:React.ComponentType|
反应组分类型
打字不够
如何解决此问题?更新
因为C是一个组件,而不是一个道具。
因此,我们可以使用两个单独的参数来定义UnauthenticatedRoute组件来处理它
interface RouteProps {}
interface AppProps {
isAuthenticated: boolean;
}
interface Props {}
const UnauthenticatedRoute = (
{ appProps, ...rest }: RouteProps & { appProps: AppProps },
C: React.ComponentType<Props>
) => {
const redirect = queryString("redirect");
return (
<Route
{...rest}
render={props =>
!appProps.isAuthenticated ? (
<C {...props} {...appProps} />
) : (
<Redirect
to={redirect === "" || redirect === null ? "/" : redirect}
/>
)
}
/>
);
};
然后可以将其用作普通类型的组件
render() {
return <Component {...this.props as P} />;
}
请参考此库的来源
而关于React.ComponentType的文章中的render函数并没有像您在我发布的代码中看到的那样直接返回组件,因此它不起作用。我试图应用文章中解释的内容,但没有用。@unludo更新,如果有其他限制,请告诉我:很好,谢谢。不过,这与原文有很大不同。
render() {
return <Component {...this.props as P} />;
}