reactjs - 如何键入一个组件,它是动态添加其道具的父组件的子组件?
问题描述
我有两个组成部分——一个是孩子,另一个是父母。父组件被设计成一个 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`
}
解决方案
到目前为止,我还没有找到让它完全工作的好方法。这里有一些代码可以将它设置在正确的方向。
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>
推荐阅读
- image - JPG 到 4 位彩色 COE/文本文件
- reactjs - 使用 docker 和 nginx 部署的 React 应用程序:/etc/nginx/conf.d/default.conf 与软件包不同
- powershell - PS:从文本文件创建多维数组 - Cisco Switch Config
- java - Spring 中未从 data.sql 加载初始数据
- reactjs - 如何使用酶笑话检查条件渲染?
- php - 无法使用 PhpSpreadsheet 读取 xlsx 文件
- xamarin.forms - 在 Xamarin.Forms 应用程序的后台使用 NSTextView
- r - 将拟合指数方程添加到 ggplot 2
- javascript - 如何将两个 JSON 对象组合在一起
- android - Wear OS 心率追踪器