我正在显示树形视图。树节点显示为加号和减号图标,这些图标显示在文本上方。如何使节点图标和节点文本对齐呢?请在下面的沙盒中找到我的代码:https://codesandbox.io/s/shy-snow-nfce4i
谢谢!
将::marker
替换为::before
,删除list-style-type
并从ul
调整padding。
::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'}}>
首先,在Node类中初始化一个Icon属性:
//ProductsTreeView.js - line 209
class Node {
description = "n/a";
id = -1;
key_id = -1;
linkpagename = "";
icon = "";
isActive = false;
nodes = [];
constructor(description, id, key_id, icon, linkpagename) {
this.description = description;
this.id = id;
this.key_id = key_id;
this.icon = icon;
this.linkpagename = linkpagename;
}
// the rest of the code...
//ProductsTreeView.js - line 236
const icon =
entity.children[
entity.children.findIndex((child) => child.name === "imageOpen")
].value;
//ProductsTreeView.js - line 250
const node = new Node(descriptionText, id, key_id, icon, linkPageName);
//ProductsTreeView.js - line 387
<StyledLI
id={node.id}
expanded={node.isActive}
isPaper={node.icon}
isLeaf={!node.nodes.length}
to={node.linkpagename}
key={node.key_id}
onClick={(event) => {
event.stopPropagation();
onToggle(node);
}}
>
然后重新调整你的CSS-in-JS:
//ProductTreeView.js - line 177
const StyledLI = styled.li`
list-style-type: none;
::before {
content: "";
display: inline-flex;
width: 16px;
height: 16px;
${({ expanded, isPaper }) => `background: url(${isPaper === "paper.gif" ? paper : (expanded ? minus : plus)})};`};
}
`;
我尝试修改您的StyledLi组件并仅使用::marker,但无济于事。然而,我成功将它们对齐如下:
const StyledLI = styled.li`
list-style-type: none;
`;
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>
);
}
}
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>