Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何在typescript声明中指定类型参数?_Reactjs_Typescript - Fatal编程技术网

Reactjs 如何在typescript声明中指定类型参数?

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&

我创建了一个React组件,它接受其子组件的一个类。此组件负责向用户提供通过OIDC协议登录的能力,如果用户已登录,则提供将用户对象作为道具传递的子对象(子对象将在API调用中使用它)

以下是我的组件的声明方式:

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>} />;