【问题标题】:How to style nested components in react?如何在反应中设置嵌套组件的样式?
【发布时间】:2021-01-12 11:57:22
【问题描述】:

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

我想为每个组件设置缩进效果(左边距:“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;

【问题讨论】:

  • 使用 CSS 类选择器有什么问题吗?如Parent &gt; Child1 &gt; Child2 {...}。当然,您需要通过呈现的 html 进行选择,而不是尝试选择组件。
  • 不知道为什么,但是在控制台中,当我尝试时,我得到“不支持的属性值”。 margin-left 属性是删除线。

标签: javascript html css reactjs


【解决方案1】:

在同时包含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>

【讨论】:

  • 由于某种原因,我无法让它工作。我添加了一个 className 或直接使用样式,但没有任何反应。你有 React 中的示例(而不是 Html)吗?谢谢
  • @Dom355,您将 className 赋予了哪个 HTML 元素?
  • 效果很好。抱歉,我在我的 CSS 文件中实施您的解决方案时犯了一个错误。
猜你喜欢
  • 2018-12-03
  • 1970-01-01
  • 2018-07-10
  • 2020-06-28
  • 2020-05-01
  • 2021-04-21
  • 2020-01-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多