首页 > 解决方案 > 如何在反应中设置嵌套组件的样式?

问题描述

我使用嵌套组件编写了一个目录。每个组件都是一个标题列表。

我想用缩进效果(margin-left:“20px”)为每个组件设置样式,以区分每个嵌套级别。

例子:

<Parent> 
-->indent <Child/>
 -->indent   <Child2/>
   -->indent    (etc.)
</Parent>

知道如何动态地做到这一点吗?

这是我的代码:

import React from "react";

const TocContent = ({ props }) => {
    return (
        <div className="TOC">
            {props.TOC.map((header) => (
                <HeaderList key={header.objectId} header={header} props={props} />
            ))}
        </div>
    );
};

const HeaderList = ({ header, props }) => {
    return (
        <div>
            <li
                onMouseDown={(e) => e.stopPropagation()}
                className="listing"
                style={{}}
                onClick={(e) =>
                    props.handleHeaderClick(
                        header.level,
                        header.treepath,
                        header.containsLaw,
                        header.sections,
                        header.secNum,
                        header.objectId,
                        header.id,
                        e.stopPropagation(),
                    )
                }
            >
                {header._id}
            </li>
            {/* // if savedIndex === CurrentParent Index */}
            {props.headerIndex === header.objectId &&
                props.headers2.map((node2) => (
                    <HeaderList key={node2.objectId} header={node2} props={props} />
                ))}
            {props.headerIndex2 === header.objectId &&
                props.headers3.map((node3) => (
                    <HeaderList key={node3.objectId} header={node3} props={props} />
                ))}
            {props.headerIndex3 === header.objectId &&
                props.headers4.map((node4) => (
                    <HeaderList header={node4} key={node4.objectId} props={props} />
                ))}
        </div>
    );
};

export default TocContent;

标签: javascripthtmlcssreactjs

解决方案


将边距(或填充)放在同时包含HeaderList' 的主要内容和子HeaderList组件的元素上(而不是像现在这样只包含主要内容)。具体来说,这将是在组件div中包装所有其他返回的内容HeaderList。边距将堆积起来,每个嵌套的标题列表将比父级缩进更多。

例如(仅 HTML 和 CSS):

.header-list {
  margin-left: 20px;
}
<div class="header-list">
  First Element
  <div class="header-list">
    Second Element
    <div class="header-list">
      Third Element
    </div>
  </div>
</div>


推荐阅读