如何筛选 props.children

How to filter the props.children

我在下面的功能组件中使用 props.children,它工作正常,因为所有 children 在 UI 中呈现良好。

function Footer(props: FooterProps) {
   return (
     <div>
        {props.children}
    </div>
   );
};

但是,我需要根据child的某些属性过滤props.children,并将它们放在不同的div中。控制台中没有错误,但 child 个组件未呈现。

function Footer(props: FooterProps) {
   return (
     <div>
        {props.children?.map(child => {
            if (child.align === "right") { //no probs with this condition, code executes as expected.
                <div> // grouping into another div
                    {child}
                </div>
            }
            else {
                { child }
            }
        })}
    </div>
   );
};

知道这里有什么问题吗?

你没有在你的 map 回调中 returning 任何东西,它正在成为一个 undefined 的数组,React 被设计为不渲染任何东西。如果您将两个预期值包装在 return 语句中,它应该按预期工作。

这是它的样子:

function Footer(props: FooterProps) {
   return (
     <div>
        {props.children?.map(child => {
            if (child.align === "right") { //no probs with this condition, code executes as expected.
                return (
                    <div> // grouping into another div
                        {child}
                    </div>
                );
            }
            else {
                return child;
            }
        })}
    </div>
   );
};

我不确定这是否真的是正确的方法,一般来说,我不鼓励在收到 child 后直接以这种方式更改它并寻找更组合的方法,但是如果您确实需要这样做,您可能应该使用 React.Children.map 方法:https://reactjs.org/docs/react-api.html#reactchildrenmap