首页 > 解决方案 > 尽管使用 React.FC,但在访问子组件时出现打字稿错误

问题描述

我有一个看起来像这样的子组件:

interface ChildProps extends AnotherInterface{
    route: string,
    exitAction: ActionCreatorWithoutPayload,
}

const ChildComponent:FC<ChildProps> = ({title, shape, route, exitAction, children}) => {
    ... other stuff
}

这个容器组件看起来像这样:

export default connect(null, {
    exitAction,
})(ChildComponent);

但是当我尝试像这样渲染组件时:

<ContainerComponent
    title={action.title}
    shape={action.shape}
    route={qaction.route}
> 
<div>Some Data</div>
</ContainerComponent>

所以这给了我以下错误:

Type '{ children: ReactNode; title: string; shape: TActionShape; route: string; }' is not assignable to type 'IntrinsicAttributes & Pick<Props, "title" | "shape" | "route">'.

Property 'children' does not exist on type 'IntrinsicAttributes & Pick<Props, "title" | "shape" | "route">'

当然,我正确导入了所有内容,也没有拼写或语法错误我上面显示的是我正在尝试做的简化版本,以便我们可以查明根本原因。

请注意,唯一的错误是由于 Children 属性,您在错误中看到的其余属性来自 AnotherInterface。

该网络应用使用 React、Redux、NextJs、ReduxToolKit 和 Typescript

标签: reactjstypescriptreduxnext.js

解决方案


如果要传递子组件,则父组件必须具有children: React.ReactNodechildren?: React.ReactNode类型,具体取决于它是必需的还是可选的。

例如:

<ContainerComponent
    title={action.title}
    shape={action.shape}
    route={action.route}
> 
<div>Some Data</div>
</ContainerComponent>

在这里,<div>Some Data</div>如果您有children: React.ReactNodeContainerComponent 类型,将通过(不抛出错误)。

此外,ContainerComponentreturn应该具有{children}或使用 React.Children。你可以在这里阅读更多关于 React.Children的信息。


推荐阅读