Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.5k views
in Technique[技术] by (71.8m points)

如何才能获取到React组件的有效(会渲染的)子组件数?

有很多列表项目,我想在他们外面给他们添加一层,给他们整体添加一个外边框,然后把外面这层外边框写成一个组件,但是当子组件返回为空的时候回出现一些问题

最开始是这样

import Item from './Item';

function foo(){
    return (
        <>
            <Item/>
            <Item/>
            <Item/>
            <Item/>
            <Item/>
            <Item/>
        </>
    )
}

现在需要给他们加一层外壳

import Item from './Item';
import Wraper from "./Wraper';

function foo(){
    return (
        <>
            <Wraper>
                <Item/>
                <Item/>
                <Item/>
            </Wraper>
            
            <Wraper>
                <Item/>
                <Item/>
                <Item/>
            </Wraper>
        </>
    )
}

这个Wraper组件有一些外边距和内边距, 如果Wraper组件里面的所有Item组件都返回null | undefined 那么这个Wraper组件就不应该渲染, 在Wraper组件里面使用React.Children.count计算出来的值永远都会3,因为这些子组件即便返回null | undefained 也是有效的子组件

所以如何才能准确计算Wraper组件实际渲染的子组件的数量 ? ? ?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
.Wraper:empty {
    display:none;
}

试试


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...