鍍金池/ 問答/HTML/ react 組件中確定是否含有某個(gè)特定的子組件

react 組件中確定是否含有某個(gè)特定的子組件

react 組件中確定是否含有某個(gè)特定的子組件

最近在寫一個(gè)組件,但是需要知道這個(gè)組件里面是否含有特定的子組件,目前找到的一種方法是使用組件的type.name的方式進(jìn)行判斷,想問一下有沒有更好的方式進(jìn)行判斷

相關(guān)代碼

 // 父組件
    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') { //這里使用child的type.name進(jìn)行判斷
                    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>
    }
}

如果有哪位前輩知道的話麻煩告知一下,感激不盡!

回答
編輯回答
柒槿年

child.type === Sider

ReactElementInstance.type = ReactComponent,React元素的type屬性即是對(duì)應(yīng)的React組件。

字符串可能重復(fù),但是class不會(huì)

2018年7月28日 11:44