我正在使用下面的代码,它可以完成工作(目前)。根据数组的长度,组件以数组元素引用作为 Prop 相互嵌套。在最里面的元素内部必须始终注入(inject)另一个元素。
const arr = ['one', 'two', 'three'];
const injectedContent = <SomeContent />;
const renderNestedSections = () => {
switch (arr.length) {
case 1:
return (
<Section name={arr[0]}>
{injectedContent}
<Section>
);
case 2:
return (
<Section name={arr[0]}>
<Section name={arr[1]}>
{injectedContent}
</Section>
</Section>
);
case 3:
return (
<Section name={arr[0]}>
<Section name={arr[1]}>
<Section name={arr[2]}>
{injectedContent}
</Section>
</Section>
</Section>
);
default:
return null;
}
}
我正在努力创建一个带有动态嵌套算法的函数。任何帮助都感激不尽。提前致谢。
最佳答案
这是我脑子里想不到的事情。也许有更好/更清晰的方法来做到这一点,但想法是迭代数组中的每个项目并向外构建,将每个部分包装在另一个部分内。
为此Array#reduce
从注入(inject)内容的累加器值开始使用。然后,您只需向上构建到最外面的部分即可。另外,因为我们是向外构建而不是向内构建,所以我们必须反转数组(请记住,这会改变数组,因此您可能需要在执行此操作之前克隆它)。
这是使用 DOM 而不是 React 的概念证明。
let arr = ['one', 'two', 'three']
// Inner Content
let content = document.createElement('div')
content.innerHTML = "Hello World"
// Algorithm
let res = arr.reverse().reduce((acc, item)=>{
let a = document.createElement('div')
a.classList.add(item)
a.appendChild(acc)
return a
}, content)
document.body.appendChild(res)
div {
padding : 10px;
color : white;
}
.one {
background-color: red;
}
.two {
background-color: green;
}
.three {
background-color: blue;
}
这是我认为 React 版本的样子,但我还没有测试过。
const arr = ['one', 'two', 'three'];
const injectedContent = <SomeContent />;
// Algorithm
let result = arr.reverse().reduce((acc, item)=>{
return (
<Section name={item}>
{acc}
</Section>
)
}, InjectedContent)
关于javascript - 动态嵌套的 React 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50888615/