【发布时间】: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 & { 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