【问题标题】:React children's when using HOC to wrap parent使用 HOC 包装父级时反应子级
【发布时间】: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 会按照我需要的方式工作

标签: react-i18next react-16


【解决方案1】:

这个问题非常愚蠢......

我将&lt;ChildComponent&gt; 导入为默认导入,即使孩子没有默认导出。

基本上

import ChildComponent from '' 而不是import { ChildComponent } from ''

【讨论】:

    【解决方案2】:

    在下面的示例中,我们在组件上设置 Component.displayName,以便我们可以在父组件中访问该属性。这是一个非常简单的示例,如果需要,可以扩展为使用一组子对象。

    const ChildComponent = () => {
        return <div>child render</div>
    }
    
    ChildComponent.displayName = "MyComponentName"
    
    const ParentComponent = ({ children }) => {
        // This is the type of component.. should output "MyComponentName"
        const childType = children.type.displayName
    
        return (
            <div>
                <h1>Render Children</h1>
    
                {children}
            </div>
        )
    }
    
    function App() {
        return (
            <ParentComponent>
                <ChildComponent />
            </ParentComponent>
        )
    }
    

    【讨论】:

    • 正如我在问题中所说,我不需要字符串...所以 displayName 不起作用。我需要生成组件的功能。同样,正常的 children > child.type 行为正是我所需要的......但在我的情况下,问题似乎是 withTranslation 和/或任何其他 HOC
    • 最重要的是,为了访问您的 displayName,我需要与我所指的完全相同的“类型”?。但同样,由于 withTranslation(或任何其他 HOC),这对我不起作用
    猜你喜欢
    • 2021-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-17
    • 2022-11-11
    • 2021-05-04
    • 1970-01-01
    • 2014-03-24
    相关资源
    最近更新 更多