Reactjs 如何在typescript声明中指定类型参数?
我创建了一个React组件,它接受其子组件的一个类。此组件负责向用户提供通过OIDC协议登录的能力,如果用户已登录,则提供将用户对象作为道具传递的子对象(子对象将在API调用中使用它) 以下是我的组件的声明方式:Reactjs 如何在typescript声明中指定类型参数?,reactjs,typescript,Reactjs,Typescript,我创建了一个React组件,它接受其子组件的一个类。此组件负责向用户提供通过OIDC协议登录的能力,如果用户已登录,则提供将用户对象作为道具传递的子对象(子对象将在API调用中使用它) 以下是我的组件的声明方式: type AuthProps = { childClass: typeof React.Component; } type AuthState = { user: Maybe<User> } class Auth extends React.Component&
type AuthProps = {
childClass: typeof React.Component;
}
type AuthState = {
user: Maybe<User>
}
class Auth extends React.Component<AuthProps, AuthState> {
}
然而,这甚至不是一个正确的语法。是否有可能以某种方式缩小
childClass
的类型?备选方案1:React.ComponentType
type AuthProps = {
childClass: React.ComponentType<{ user: Maybe<User> }>;
};
class Auth extends React.Component<AuthProps, AuthState> {
render() {
return <this.props.childClass user={this.state.user} />;
}
}
这是首选和更安全的选择。给定客户端传递了一个内联组件,如
const App = () => <Auth childClass={props => <div>{props.user}</div>} />;
const-App=()=>用于相关文章)
type AuthProps = {
childClass: React.ComponentType<{ user: Maybe<User> }>;
};
class Auth extends React.Component<AuthProps, AuthState> {
render() {
return <this.props.childClass user={this.state.user} />;
}
}
type AuthProps2 = {
childClass: (user: Maybe<User>) => JSX.Element;
};
class Auth2 extends React.Component<AuthProps2, AuthState> {
render() {
return this.props.childClass(this.state.user);
}
}
const App = () => <Auth childClass={props => <div>{props.user}</div>} />;