javascript - ReactJS - React.Children.forEach - 我可以获得子组件名称吗?

标签 javascript reactjs

我有一个包含许多子项的 React (15.5.4) 组件,其中一些是 HTML 元素,一些是其他 React 组件。

我正在使用服务器渲染并且需要在服务器和客户端上有相同的行为。客户端将使用 React 的生产构建。

我需要遍历子组件并确定特定类型的 React 组件。所以我的第一个想法是使用 React.Children.forEach() 进行迭代并查找组件名称。

React.Children.forEach(this.props.children, child => {
  console.log('name =', child.name)
})

似乎 child.namechild.displayName 不存在。

现在,child.type 存在了,它要么是一个字符串(对于 HTML 元素),如 "ul",要么是一个函数(对于 React 组件)。

当它是一个函数时,我可以像这样使用 lodash/get const type = get(child, 'type.name', '') 来获取组件姓名。 但是,这似乎只在服务器上有效,而不是在客户端生产构建中,它返回一个字符串:"t"。看起来开发版本使用我的组件名称作为函数,但生产版本将其重命名为 t()。所以我不能使用 child.type.name

我如何:

  1. 遍历子组件并识别特定类型的组件..?
  2. 哪个在开发和生产 React 构建中都有效..?

最佳答案

您可以在属性 displayName 中设置组件的名称。如果您使用的是 ES6 类,则可以将名为 displayName 的静态属性设置到组件的类中。然后,您将能够使用 child.type.displayName 获取 child 的名字。

const FirstChild = ({ name }) => <li>{name}</li>;
FirstChild.displayName = 'FirstChild';

const SecondChild = ({ name }) => <li>{name}</li>;
SecondChild.displayName = 'SecondChild';

class ThirdChild extends React.Component {
  static displayName = 'ThirdChild';
  
  render() {
    return (
      <li>{this.props.name}</li>
    );
  }
  
}

class Parent extends React.Component {
  componentDidMount() {
    React.Children.forEach(this.props.children, child => {
      console.log('name =', child.type.displayName);
    })
  }
  
  render() {
    return (
      <ul>{this.props.children}</ul>
    );
  }
}

class App extends React.Component {
  render() {
    return (
      <Parent>
        <FirstChild name='1st child value' />
        <SecondChild name='2nd child value' />
        <ThirdChild name='3rd child value' />
      </Parent>
    );
  }
}


ReactDOM.render(<App />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

关于javascript - ReactJS - React.Children.forEach - 我可以获得子组件名称吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43913054/

相关文章:

javascript - 对内部有两个对象的数组进行排序

reactjs - 有人有这个问题吗? "To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method"

javascript - 一个 react 应用程序导入到另一个 react 应用程序中?

javascript - 使用 Typescript 接口(interface) - 错误 : property does not exist

javascript - Google Chrome 和 Firefox 的 jquery ajax html 问题

javascript - 无法访问javascript自定义对象中函数内的元素

javascript - JavaScript 中的定时器控制

javascript - 如何在 Javascript 中更改关键帧的 CSS 属性?

javascript - 展开 <UL> <LI> 工作正常,但如果有链接,它也会默认单击然后展开,但情况并非如此

javascript - 为什么 JSX props 不应该使用箭头函数或绑定(bind)?