首页 > 解决方案 > 如何键入一个组件,它是动态添加其道具的父组件的子组件?

问题描述

我有两个组成部分——一个是孩子,另一个是父母。父组件被设计成一个 HOC,它对数据进行 ajax 调用,然后将数据传递给它的子组件。它传递给孩子的道具是React.CloneElement通过this.props.children.

关于流程,它无法解释/查看我在重新克隆时添加的其他道具。

我该如何度过这个难关?

两个组件之间的关系。

<ParentComponent>
     </ChildComponent />
</ParentComponent>
const ParentComponent = (props) => {
     // code
     return (
          <>
               {React.cloneElement(this.props.children, { extraProps }}
          <>
      );
}

type PropTypes = {
     extraProps: string, // flow complains, and I don't know how to get it to recognize that the extraProps is added dynamically.
};

const ChildComponent = (props) => {
    // code that uses the additional `extraProps`
}

标签: reactjsflowtype

解决方案


到目前为止,我还没有找到让它完全工作的好方法。这里有一些代码可以将它设置在正确的方向。

import * as React from 'react'

const ParentComponent = (props: { children: React.Element<typeof ChildComponent> }) => {
     return (React.cloneElement(props.children, { extraProps: 'hello' }));
     // return (React.cloneElement(props.children, { extraProps: 1 }));  // <-- this will error
}

type PropTypes = {
     extraProps?: string, // not great because you'll still have to check presence, but at least it provides
                          // type checking on extraProps in the ParentComponent
};

const ChildComponent = (props: PropTypes) => {
  return <p>{props.extraProps}</p>
}

<ParentComponent><ChildComponent /></ParentComponent>

流试


推荐阅读