determine whether there is a specific subcomponent in the react component
recently, I am writing a component, but I need to know whether this component contains specific subcomponents. One of the ways we have found is to use the type.name
way of the component to judge. I would like to ask if there is a better way to judge
related codes
//
class Layout extends Component {
static propTypes = {
accordion: PropTypes.bool,
}
static defaultProps = {
accordion: false,
}
// Sider
judeSider = () => {
let hasSider = false
React.Children.forEach(this.props.children, (child) => {
if (child.type.name === "Sider") { //childtype.name
hasSider = true
}
})
return hasSider
}
render() {
const hasSider = this.judeSider()
return <div className={hasSider ? styles.layoutHasSider : styles.layout}>{this.props.children}</div>
}
}
//
class Sider extends Component {
static propTypes = {
collapsible: PropTypes.bool,
collapsed: PropTypes.bool,
width: PropTypes.string
}
static defaultProps = {
collapsible: false,
collapsed: false,
width: "200px"
}
render() {
const { className, children, style, width, collapsible, collapsed, ...others } = this.props
const cls = classNames(className, styles.sider, {
[styles.collapsible]: collapsible,
[styles.collapsed]: collapsed
})
const realStyle = collapsed ? {...style, width:"0px"} : {...style, width: width}
return <div
className={cls}
style={realStyle}
{...others}
>
{children}
</div>
}
}
if any of the seniors know, please let me know, thank you very much!