首页 > 解决方案 > 使用子组件和 react-redux (React typesciprt)

问题描述

如果电子邮件经过验证(来自 redux 的道具),则会VerifiedComp呈现组件。children如果电子邮件未通过验证,则会显示一个按钮。我遇到的问题是打字稿要求父组件中的孩子。

这是CreatePage父组件的组件。

type StateTypes = {
  history: { push: (link: string) => {} };
};

const mapStateToProps = ({ history }: StateTypes) => ({
  history,
});

const connector = connect(mapStateToProps, { startCreateMovie });
type PropsFromRedux = ConnectedProps<typeof connector>;

export const CreatePage = ({ history, startCreateMovie }: PropsFromRedux) => {
  return (
    <VerifiedComp>
      <CreateForm ... />
    </VerifiedComp>
  );
};

这是VerifiedComp.

type PropTypes = {
  children: React.ReactNode
};

type StateTypes = {
  auth: { user: { emailVerified: boolean }, providerData: {email: string} };
}

const mapStateToProps = (state: StateTypes, props: PropTypes) => ({
  email: state.auth.providerData.email,
  children: props.children,
  emailVerified: state.auth.user.emailVerified
});

const connector = connect(mapStateToProps);
type PropsFromRedux = ConnectedProps<typeof connector>;

const VerifiedComp: React.FC<PropsFromRedux> = (props: PropsFromRedux) => {
  return props.emailVerified ? (
    <React.Fragment>{props.children}</React.Fragment>
  ) : (
    <Box>.....</Box>
  )

这是完整的问题

Type '{ children: Element; }' is missing the following properties from type '{ email: string; emailVerified: boolean; }': email, emailVerified  TS2739

    19 | export const CreatePage = ({ history, startCreateMovie }: PropsFromRedux) => {
    20 |   return (
  > 21 |     <VerifiedComp>
       |      ^
    22 |       <MovieForm

标签: javascriptreactjsreduxreact-reduxreact-typescript

解决方案


这是因为您已将儿童财产设为强制性

type PropTypes = {
children: React.ReactNode
};

而是将其设为可选,如下所示:

type PropTypes = {
children?: React.ReactNode
};

推荐阅读