小编Has*_*rak的帖子

循环遍历 React Children 的每个嵌套子级

我正在尝试创建一个表组件,该组件将为其特定子组件提供一些特殊的类名。

    const BasicTable = ({ children }) => {
        const RenderChild = Children.map(children, (el) => {
            const child = el;
    
            if (child !== null) {
                if (child.props.originalType !== "th") {
                    return <child.type {...child.props} className="th" />;
                }
    
                return <child.type {...child.props} />;
            }
            return null;
        });
    
        return (
            <div className="table-responsive">
                <table className="table w-full bg-transparent">{RenderChild}</table>
            </div>
        );
    };
Run Code Online (Sandbox Code Playgroud)

这是我的组件,我想像这样使用它。

    <BasicTable>
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Position</th>
                <th>Salary</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>dsfa</td>
                <td>dsfa</td>
                <td>dsfa</td>
                <td>dsfa</td>
            </tr>
        </tbody>
    </BasicTable>
Run Code Online (Sandbox Code Playgroud)

但这里的问题是我的Children.map函数仅循环其直接子级。如何将 props 传递给其嵌套子级(th、td、...等)

javascript reactjs

6
推荐指数
2
解决办法
1万
查看次数

标签 统计

javascript ×1

reactjs ×1