如果我有一个具有2个层次结构的对象:
const data = [
{
name: "Parent 1",
children: [
{
name: "Child 1"
},
{
name: "Child 2"
}
]
},
{
name: "Parent 2",
children: [
{
name: "Child 3"
},
{
name: "Child 4"
}
]
}
];
然后我可以在React中渲染每个项目:
const Child = ({ children }) => {
if (!children) return null;
return (
<ul>
{children.map(item => {
return <li key={item.name}>{item.name}</li>;
})}
</ul>
);
};
const Parent = ({ item }) => {
return (
<>
<li>{item.name}</li>
<Child children={item.children} />
</>
);
};
const App = () => {
return (
<ul>
{data.map(item => {
return <Parent key={item.name} item={item} />;
})}
</ul>
);
};
但是,如果我不知道嵌套的深度,有没有一种方法可以递归地呈现React组件,以便呈现所有数据?
这演示了3个嵌套级别,但可以想象有更多的嵌套级别:
const data = [
{
name: "Parent 1",
children: [
{
name: "Child 1",
children: [
{
name: "Sub-child 1"
},
{
name: "Sub-child 2"
}
]
},
{
name: "Child 2"
}
]
},
{
name: "Parent 2",
children: [
{
name: "Child 3"
},
{
name: "Child 4"
}
]
}
];
答案 0 :(得分:1)
这与使用递归函数调用相同。使用如下功能:
const Children = (props) => <>
<li>
<p>{props.children.name}</p>
{props.children.children && <ul>{renderChild(props.children.children)}</ul>}
</li>
</>;
const renderChild = item =>
item.map(it => (
<Children children={it} />
));
function App() {
return (
<div className="App">
<h1>Nested Children</h1>
<ul>{renderChild(data)}</ul>
</div>
);
}
此外,我还觉得children
是React中的保留prop
。请检查一次。
预览