【发布时间】:2021-03-21 09:59:16
【问题描述】:
所以我使用 react 从 json 文件中呈现 NESTED 无序列表。为了便于阅读,我希望以每行交替的背景颜色显示它们。 所以是这样的:
1 (white)
2 (gray)
3 (white)
4 (gray)
5 (white)
6 (gray)
7 (white)
我尝试使用纯 CSS,但它似乎不起作用,因为 nth-of-type() 只检查相对索引。仅供参考,它看起来像这样:
1 (white)
2 (gray)
1 (white)
1 (white)
2 (gray)
2 (gray)
3 (white)
然后我尝试在递归渲染函数中使用计数器来确定当前行是偶数还是奇数:
class Tree extends React.Component{
renderChild = (child, count=0, key=0) => {
//if
if (child.children) {
return (
//I need some state management so I need another component. Kind of like double recursion.
<Subtree renderChild={this.renderChild} child={child} count={count} key={key}/>
);
}
else if (child.name) {
return <Node child={child} count={count} key={key}/>;
}
count += 1
return null;
}
render(){
return (
<div className="tree">
{this.renderChild(this.props.data)}
</div>
)
}
}
function Subtree (props){
// just an example of many states it's supposed to have so I have to put it in a separate component
// collapse will trigger recount since it will change the even/odd of subsequent nodes
const [ collapsed, setCollapsed ] = useState(false)
return (
<figure>
//title for the ul. needs to be counted in the sequence as well.
<figcaption onClick={()=>setCollapsed(!collapsed)} className={`${(props.count % 2) === 1 ? "gray field" : "field"}`}>
{props.child.name}
</figcaption>
{collapsed === false
?
<ul>
//needs to be async here
{props.child.children.map((item, index) => {
//calls to parent to recursively render all the list
//add 1 counting for the title
//need to wait for this to finish before moving to the next item.
return props.renderChild(item, props.count + index + 1, uuid());
})}
</ul>
:
null
}
</figure>
);
}
function Node (props){
return(
//check if count is even or odd
<li className={`${props.count % 2===1 ? "gray field" : "field"}`}>
{props.child.name}
</li>
)
}
但是,正如您已经知道的那样,序列更加混乱,因为序列中相同级别的流程节点的递归类型。所以我所拥有的是这样的:
1 (white)
2 (gray)
4 (gray)
6 (gray)
7 (white)
5 (white)
3 (white)
我知道我可以展平树,然后使用匹配字段来确定偶数/奇数。但它在时间和空间方面似乎都非常低效。
【问题讨论】:
标签: javascript css reactjs