【问题标题】:React + TypeScript: Passing React Component as Props, rendering with props [Error: TS2339]React + TypeScript:将 React 组件作为道具传递,使用道具进行渲染 [错误:TS2339]
【发布时间】:2019-03-20 14:11:44
【问题描述】:

我正在使用 React + TypeScript。 我有一个场景,我必须将 React.SFC 组件传递给另一个组件。我正在这样做:

Container.tsx

import ChildComp from './ChildComp';
<ParentComponent CustomComp={ ChildComp } someArray={ [1, 2] } />

现在的问题是,我想在 ParentComponent 内部使用 someArray 值迭代这个 ChildComp 组件。

这个子组件有它自己的 prop someValue,我已经向它添加了类型,就像这个子组件可以接受的一样,我在传递这个 prop 时在 Parent 中迭代它。

ParentComponent.tsx

const content = someArray.map((value, index) => (
  <CustomComp someValue={ value } key={ index } />
));
{ content }

但我遇到了错误,TS2339: Property 'someValue' does not exist on type 'IntrinsicAttributes &amp; { children?: ReactNode; }'.

虽然,如果我在导入它的Container.tsx 中直接使用上述迭代,它工作正常。但如果我将它传递给另一个组件,则不起作用。 我在这里遗漏了什么吗?

注意:由于相同的迭代正在Container.tsx 上工作,我将迭代的内容传递给ParentComponent 并将其渲染为变量:

{ CustomComp }

这可行,但我想知道为什么其他解决方案不起作用。

更多详情

ChildComp.tsx

type Props = {
   someValue: number,
};

const ChildComp: React.SFC<Props> = ({ someValue }) => {
   return (
      // Content
      { someValue }
   )
}

CustomComp 的类型,在ParentComponent:

type Props = {
   CustomComp?: React.ReactNode | null
};

之前是React.ComponentType,但是我报错了,所以我改了ReactNode,因为我现在直接传递内容。

【问题讨论】:

    标签: javascript reactjs typescript react-props react-component


    【解决方案1】:

    CustomComp 属性输入不正确。它接受一个组件 (CustomComp={ ChildComp }),而不是一个元素 (CustomComp={ &lt;ChildComp /&gt; })。在这种情况下,它不是React.ReactNode,而是React.ComponentType

    它也不是随机组件,而是接受someValue 属性的特定组件。 ParentComponent props 可能应该输入为:

    type ParentCompProps = {
       CustomComp: React.ComponentType<ChildCompProps>,
       someArray: number[]
    };
    

    【讨论】:

    • 我将它作为 { ChildComp } 传递,因为我想在 ParentComponent 中呈现它。并且由于它需要在ParentComponent 内的道具,这就是为什么没有作为{ &lt;ChildComp /&gt; } 传递的原因。但我认为如果我定义ChildCompProps,它会解决问题。让我测试一下。
    • 谢谢,它解决了这个问题。这就是我所缺少的,CustomComp 的道具验证。我只是定义CustomComp: React.ComponentType,需要添加&lt;ChildCompProps&gt;
    猜你喜欢
    • 2018-08-22
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 2018-08-01
    • 1970-01-01
    • 2021-09-08
    • 1970-01-01
    • 2020-10-19
    相关资源
    最近更新 更多