【问题标题】:React: how to align icons with text?React:如何将图标与文本对齐?
【发布时间】:2022-11-16 19:04:56
【问题描述】:

我正在显示树视图。树节点显示有加号和减号图标。这些图标显示在文字上方?如何在同一行中对齐节点图标和节点文本? 请找到我的沙盒:https://codesandbox.io/s/shy-snow-nfce4i

谢谢

【问题讨论】:

  • 请至少将问题的核心作为代码包含在问题本身中,外部链接也可以,但不应该是我们可以看到代码的唯一地方。
  • 我试着把代码和问题放在一起。它给了我发布代码的问题。 Sandbox 是正在运行的示例,它准确地显示了问题。
  • 请检查我更新的答案。

标签: javascript css reactjs


【解决方案1】:

您可以使用 before 伪元素代替标记。这是更灵活的方式。

// css
.list {
  list-style: none;
}

.item {
   position: relative;
   padding-left: 20px;
}

.item::before {
  top: 0;
  left: 0;
  position: absolute;
  content: url(https://uploads.codesandbox.io/uploads/user/25a43e4c-a00e-4028-8cde-b4bc9a9987f9/pkCB-plus.gif);
}

// render
<ul className="list">
  <li className="item">Some text 1</li>
  <li className="item">Some text 2</li>
  <li className="item">Some text 3</li>
</ul>

【讨论】:

  • 嗨 Dmitriy,请检查我的沙箱,我正在显示加号减号图标。图标未与文本对齐。请帮助如何修复我的代码
【解决方案2】:

我尝试修改您的 StyledLi 组件并专门使用 ::marker,但无济于事。但是,我设法将它们对齐:

   const StyledLI = styled.li`
      list-style-type: none;
    `;

在 TreeNode 中:

class TreeNode extends React.Component {
  render() {
    const { node, onToggle } = this.props;

    const activeChildren =
      node.isActive && node.nodes.length ? (
        <ul>
          {node.nodes.map((node) => (
            <TreeNode
              id={node.id}
              key={node.key_id}
              node={node}
              onToggle={onToggle}
            />
          ))}
        </ul>
      ) : null;

    return (
      <StyledLI
        id={node.id}
        expanded={node.isActive}
        isLeaf={!node.nodes.length}
        to={node.linkpagename}
        key={node.key_id}
        onClick={(event) => {
          event.stopPropagation();
          onToggle(node);
        }}
      >
        <div style={{
          display: 'flex',
          alignItems: 'center'
        }}>
          <img src={node.isActive ? minus : plus} />

          <Link
            to={node.linkpagename}
            style={{ textDecoration: "none", color: "#000000" }}
          >
            {node.description}
          </Link>{" "}
          - {node.key_id} - {node.linkpagename}
        </div>

        {activeChildren}
      </StyledLI>
    );
  }
}

您可以将其复制粘贴到您的代码中。

【讨论】:

    【解决方案3】:

    ::marker替换为::before,删除list-style-type并调整ul的填充。 ::marker 不能使用伪元素那样多的属性进行修改,因此为了设置样式,您需要切换到伪元素。

    //ProductsTreeView.js  - line 177
    const StyledLI = styled.li`
      list-style-type: none;
      ::before {
        content: "";
        display: inline-flex;
        width: 16px;
        height: 16px;
        ${({ expanded }) =>
          `background: url(${expanded ? minus : plus})};`};
      }
    `;
    
    //ProductsTreeView.js  - line 294
    <ul style={{paddingLeft: '1.8rem'}}>
    

    【讨论】:

      猜你喜欢
      • 2021-06-22
      • 2011-03-07
      • 1970-01-01
      • 2015-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-29
      • 2014-04-28
      相关资源
      最近更新 更多