React + TypeScript:将 React 组件作为道具传递,使用道具渲染 [错误:TS2339]

Rah*_*ore 2 javascript typescript reactjs react-props react-component

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

容器.tsx

import ChildComp from './ChildComp';
<ParentComponent CustomComp={ ChildComp } someArray={ [1, 2] } />
Run Code Online (Sandbox Code Playgroud)

现在的问题是,我想ChildCompsomeArray值迭代这个组件, inside ParentComponent

这个子组件有它自己的 prop someValue,我已经向它添加了类型,比如这个子组件可以接受的类型,并且我在 Parent 内部迭代它时传递了这个 prop。

父组件.tsx

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

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

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

注意:由于相同的迭代正在处理Container.tsx,我将迭代的内容传递给ParentComponent并像变量一样呈现它:

{ CustomComp }
Run Code Online (Sandbox Code Playgroud)

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

更多细节

ChildComp.tsx

type Props = {
   someValue: number,
};

const ChildComp: React.SFC<Props> = ({ someValue }) => {
   return (
      // Content
      { someValue }
   )
}
Run Code Online (Sandbox Code Playgroud)

CustomComp 的类型,在ParentComponent

type Props = {
   CustomComp?: React.ReactNode | null
};
Run Code Online (Sandbox Code Playgroud)

在它之前React.ComponentType,但我收到错误,所以我改变了它 ReactNode,因为我现在直接传递内容。

Est*_*ask 5

CustomComp道具输入不正确。它接受一个组件 ( CustomComp={ ChildComp }),而不是一个元素 ( CustomComp={ <ChildComp /> })。在这种情况下,它不是React.ReactNode但是React.ComponentType

它也不是随机组件,而是接受someValueprop 的特定组件。ParentComponentprops 可能应该输入为:

type ParentCompProps = {
   CustomComp: React.ComponentType<ChildCompProps>,
   someArray: number[]
};
Run Code Online (Sandbox Code Playgroud)