【问题标题】:Can I do typescript props validation for a component wrapped inside a HOC?我可以对包装在 HOC 中的组件进行 typescript props 验证吗?
【发布时间】:2020-03-11 06:09:12
【问题描述】:

我正在使用 React HOC 编写组件,但在使用 typescript 验证道具时出错。 错误如下

类型'{类型:字符串; imgUrl:任何; vidUrl:任何; }' 不可赋值 输入'IntrinsicAttributes & Pick & { 孩子?:ReactNode;}'。

我的组件是什么样的(示例):

type Props = {
type: string;
imgUrl: any;
vidUrl: any;
}
const Component = ({type,imgUrl,vidUrl}:Props)=> (
<div>.....
.....
</div>
)
export defualt withTranslation('common')(Component);

【问题讨论】:

    标签: reactjs typescript react-props react-tsx


    【解决方案1】:

    您必须为组件提供正确的类型。

    import { withTranslation, WithTranslation } from 'react-i18next';
    import React from "react";
    type Props = {
      type: string;
      imgUrl: any;
      vidUrl: any;
      }
      const Component: React.FC<Props & WithTranslation> = ({type,imgUrl,vidUrl})=> (
      <div>.....
      .....
      </div>
      )
      const withTranslationComponent = withTranslation('common')(Component);
      export default withTranslationComponent;
    

    【讨论】:

    • 哦,所以我必须将我的类型与 HOC 的类型结合起来。我的是next-i18n-next,所以我会尝试一下。谢谢!
    • 作为更新,我想补充一点,在功能组件中使用 useTranslation 钩子很好。
    猜你喜欢
    • 2018-04-23
    • 2015-11-14
    • 1970-01-01
    • 2014-09-16
    • 1970-01-01
    • 2020-10-07
    • 1970-01-01
    • 2020-01-26
    • 2022-07-13
    相关资源
    最近更新 更多