【发布时间】:2019-06-20 00:36:29
【问题描述】:
我使用的是 React 16.8.6,我有以下结构:
page.js
<ParentComponent id="testData">
<ChildComponent value={data => data.text} />
</ParentComponent>
parentComponent.tsx
export default class ParentComponent extends React.PureComponent<IParentProps> {
...
render() {
const items = this.props.children;
<MiddleComponent items={items} />
}
}
父容器.ts
import { withTranslation } from 'react-i18next';
import ParentComponent from './ParentComponent';
export default withTranslation()(ParentComponent);
我需要知道 MiddleComponent 内部每个子元素的类型(不是作为字符串,而是作为 React 元素,因为我将基于它创建一个新元素)(所以, 在这种情况下我应该有ChildComponent),但是当我用 chrome 检查时,我所有的孩子都有一个I18nextWithTranslation 类型...
知道如何解决这个问题吗?或者如果这可能是一个已知的错误?
如果我根本不使用任何 hoc,当我写 child.type 时,它会返回给我 ChildComponent(props)。但是,当我使用 hocs 包装父级时,情况并非如此......
【问题讨论】:
-
你需要知道元素的类型是什么意思?您需要知道它是什么类型的 HTML 元素吗?
-
另外,你想在这个组件树中的哪个位置获取元素的类型?
-
在 render() 内部,我需要获取哪个组件是子组件。所以,如果父母有 2 个孩子 'Child1' 'Child2' 我需要组件的类型......
-
你能在组件上分配一个 displayName 并检查它吗?请参阅下面的答案。
-
不,displayName只会给我一个String,我需要child.type可以返回的组件函数。如果不涉及 HOC 元素,child.type 会按照我需要的方式工作