[英]How to get children type in react
I'm trying to make my own Tabs
component, so that I can use tabs in my app.我正在尝试制作自己的
Tabs
组件,以便可以在我的应用程序中使用选项卡。 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?我的
console.log
永远不会返回“Tab Link”,它总是返回undefined
,为什么?
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. 在这种情况下,您无需显式定义displayName。
https://jsfiddle.net/lustoykov/u1twznw7/1/ https://jsfiddle.net/lustoykov/u1twznw7/1/
It's undefined
because displayName
should be a static
property. 它是
undefined
因为displayName
应该是一个static
属性。
class TabLink extends React.Component {
constructor(props) {
super(props)
}
render() {
return (
<div className="tab-link"></div>
)
}
}
TabLink.displayName = 'Tab Link'
You can use the already defined name
property: 您可以使用已定义的
name
属性:
if (x.type.name === TabLink.name) {
return x
}
I recommend to use TabLink.name
instead of 'TabLink'
string for better maintenance. 我建议使用
TabLink.name
而不是'TabLink'
字符串以便更好地进行维护。
See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name 请参阅: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
I'm wondering why does your Tabs
component need to know how to render each children.我想知道为什么您的
Tabs
组件需要知道如何呈现每个孩子。
You could have a specific component for each type of tab, with their own styles and with 2 props: isSelected
and onSelect
.您可以为每种类型的选项卡设置一个特定组件,使用它们自己的 styles 和 2 个道具:
isSelected
和onSelect
。
Then the Tabs
would only:然后
Tabs
只会:
onSelect
of each tab (to update the selectedTab state and to pass true in the isSelected
prop of the correct tab)onSelect
来控制选项卡选择(更新 selectedTab state 并在正确选项卡的isSelected
属性中传递 true)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.