How to get children type in react

≯℡__Kan透↙ 提交于 2021-02-20 09:22:14

问题


I'm trying to make my own Tabs component, so that I can use tabs in my app. However I seem to be having issues trying to extract the child components I need by type.

import React from 'react'

export class Tabs extends React.Component {
  render() {
    let children = this.props.children
    let tablinks = React.Children.map(children, x => {
      console.log(x.type.displayName) // Always undefined
      if (x.type.displayName == 'Tab Link') {
        return x
      }
    })

    return (
      <div className="tabs"></div>
    )
  }
}

export class TabLink extends React.Component {
  constructor(props) {
    super(props)
    this.displayName = 'Tab Link'
  }
  render() {
    return (
      <div className="tab-link"></div>
    )
  }
}

<Tabs>
    <TabLink path="tab1">Test</TabLink>
    <TabLink path="tab2">Test2</TabLink>
</Tabs>

My console.log never returns "Tab Link", it always returns undefined, why?


回答1:


As an alternative you could use

console.log(x.type.name) // this would be 'TabLink'

You don't need to explicitly define displayName in this case.

https://jsfiddle.net/lustoykov/u1twznw7/1/




回答2:


It's undefined because displayName should be a static property.

class TabLink extends React.Component { 
  constructor(props) {
    super(props)
  }
  render() {
    return (
      <div className="tab-link"></div>
    )
  }
} 
TabLink.displayName = 'Tab Link'

jsfiddle (check the console)




回答3:


You can use the already defined name property:

if (x.type.name === TabLink.name) {
    return x
}

I recommend to use TabLink.name instead of 'TabLink' string for better maintenance.

See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name



来源:https://stackoverflow.com/questions/39212960/how-to-get-children-type-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!