javascript - 动态嵌套的 React 组件

标签 javascript reactjs

我正在使用下面的代码,它可以完成工作(目前)。根据数组的长度,组件以数组元素引用作为 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/

相关文章:

Javascript 和 Firebase 3 - 使用电子邮件和密码创建用户

Javascript 变量不更新值

javascript - 在 React Native Navigation V2 中添加 Tab 导航

javascript - 我怎样才能让箭头函数工作?

javascript - 授权回调错误

javascript - 序列化年份和月份

javascript - 为什么 TypeScript 使用对象属性赋值作为对象键并使用变量赋值作为函数参数?

javascript - 为什么我的状态没有改变,为什么我对 {store.getState()} 的引用根本没有出现?

javascript - TextInput 中的值没有改变?

javascript - 如何在 Draft.js 中插入/上传图像(更新实体和 block )?