javascript - 如何在反应中设置嵌套组件的样式?
问题描述
我使用嵌套组件编写了一个目录。每个组件都是一个标题列表。
我想用缩进效果(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;
解决方案
将边距(或填充)放在同时包含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>
推荐阅读
- matplotlib - 在新页面中将图形和/或文本附加到现有 pdf (python)
- java - Redisson Hibernate Cache Module 是否在多个容器中共享相同的数据?
- ios - 滑动以删除表格视图中具有多节的行?
- java - 在 ignite 中启用身份验证
- asp.net - EF 操作上的 ASP.NET MVC 异步等待。如何调试以及如何处理错误?
- ios - Xcode模拟器XS:为什么XS iPhone上的边框在截图中变成了一个矩形?
- asp.net-mvc - 如何使用 asp.net mvc 从头开始添加用户角色
- plotly - 用 plotly 从 2D 直方图填充 3D 直方图
- javascript - 在后台选项卡中打开链接而不会失去焦点
- widget - 一种使用鼠标滚动布局小部件的方法?