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

前端之家收集整理的这篇文章主要介绍了javascript – ReactJS – React.Children.forEach – 我可以获取子组件名称吗?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个包含许多子节点的React(15.5.4)组件,其中一些是 HTML元素,另一些是其他React组件.

我正在使用服务器渲染,并且需要在服务器和客户端上执行相同的操作.客户端将使用React的生产版本.

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

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

似乎child.name和child.displayName不存在.

现在,child.type存在,并且是一个字符串(对于HTML元素),如“ul”或函数(对于React组件).

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

我如何能:

>迭代组件子组件并识别特定类型的组件..?
>哪个适用于开发和生产React构建..?

解决方法

您可以在属性displayName中设置组件的名称.如果您正在使用ES6类,则可以将名为displayName的静态属性设置为组件的类.然后,您将能够使用child.type.displayName获取名称.
  1. const FirstChild = ({ name }) => <li>{name}</li>;
  2. FirstChild.displayName = 'FirstChild';
  3.  
  4. const SecondChild = ({ name }) => <li>{name}</li>;
  5. SecondChild.displayName = 'SecondChild';
  6.  
  7. class ThirdChild extends React.Component {
  8. static displayName = 'ThirdChild';
  9. render() {
  10. return (
  11. <li>{this.props.name}</li>
  12. );
  13. }
  14. }
  15.  
  16. class Parent extends React.Component {
  17. componentDidMount() {
  18. React.Children.forEach(this.props.children,child => {
  19. console.log('name =',child.type.displayName);
  20. })
  21. }
  22. render() {
  23. return (
  24. <ul>{this.props.children}</ul>
  25. );
  26. }
  27. }
  28.  
  29. class App extends React.Component {
  30. render() {
  31. return (
  32. <Parent>
  33. <FirstChild name='1st child value' />
  34. <SecondChild name='2nd child value' />
  35. <ThirdChild name='3rd child value' />
  36. </Parent>
  37. );
  38. }
  39. }
  40.  
  41.  
  42. ReactDOM.render(<App />,document.getElementById("app"));
  1. <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
  2. <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
  3. <div id="app"></div>

猜你在找的JavaScript相关文章