React - 替换props.children

时间:2017-01-07 15:59:00

标签: reactjs

如另一个question所示,可以使用React.Children循环子元素。 map 。我正在寻找一种递归遍历子树的方法( props.children.props.children ... )和用其他类型的元素替换某些元素。它将发生在更高阶组件的渲染函数中。

非常感谢任何帮助和想法!

1 个答案:

答案 0 :(得分:1)

您可以构建一个递归包装器组件,以替换其拥有的所有子组件,并以相同的方式包装其子组件。替换将以递归方式继续进行,直到子元素不再有子元素为止。

这是此类组件的示例。它将<p>元素替换为<span>元素。

const RecursiveWrapper = props => {
    const wrappedChildren = React.Children.map(
        props.children,
        child => {
            const type = child.type === 'p' ? 'span' : child.type
            if (child.props && child.props.children) {
                return React.cloneElement(
                    {
                        ...child,
                        type // substitute original type
                    },
                    {
                        ...child.props,
                        // Wrap grandchildren too
                        children: (
                            <RecursiveWrapper>
                                {child.props.children}
                            </RecursiveWrapper>
                        )
                    }
                )
            }
            return child
        }
    )
    return (
        <React.Fragment>
            {wrappedChildren}
        </React.Fragment>
    )
}

您也可以使用相同的一般思想注入其他道具。