首页 > 解决方案 > 动态嵌套的 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;
  }
}

我正在努力使用动态嵌套的算法创建一个函数。任何帮助都感激不尽。提前致谢。

标签: javascriptreactjs

解决方案


这是我头顶上的东西。也许有更好/更清晰的方法来做到这一点,但想法是您遍历数组中的每个项目并向外构建,将每个部分包装在另一个部分中。

要做到这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)

推荐阅读