javascript - 动态嵌套的 React 组件
问题描述
我正在使用下面的代码,它完成了这项工作(目前)。根据数组的长度,组件以数组元素引用作为道具相互嵌套。在最里面的元素内必须始终注入另一个元素。
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
一点,从您注入的内容的累加器值开始使用。然后,您只需向上构建最外层部分。此外,因为我们是向外构建而不是向内构建,所以我们必须反转数组(请记住,这会改变数组,因此您可能希望在执行此操作之前克隆它)。
这是使用 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)
推荐阅读
- mysql - 使用 2 个选择优化 SQL 查询
- python - 重置 Tkinter 窗口,恢复小部件
- r - 使用 testthat,在哪里放置自定义跳过功能?
- java - 带有 maven 的 Java 11/12 Javadoc 导致不生成用于测试的 Javadocs
- php - Laravel Blade 中的访问模型
- python - 在 NumPy 数组中用 ```[i,i,i]``` 快速替换元素 i 的 Pythonic 方法?
- html - Woocommerce 自定义开始评分
- java - 如何将一个 blueprint.xml 中的单例 bean 注入到单独的 blueprint.xml 中?
- java - 如何在 android 中创建一个切换应用程序,如谷歌翻译器(本机屏幕上的对话框)
- flutter - Material Icons 中的 Pin Icon 叫什么?