简体   繁体   English

如何在 React 中基于包含组件的数组动态创建组件树?

[英]How to dynamically create a component tree in React based on an array that contains components?

I have a components array.我有一个组件数组。

const components = [
  A,
  B,
  C,
]

Then I want to render this components like this:然后我想像这样渲染这些组件:

return (
  <A>
    <B>
      <C>
      </C>
    </B>
  </A>
)

But I can add a new component or switch the order of the components.但我可以添加一个新组件或切换组件的顺序。 I want to render this component tree in the same order as the components array.我想以与组件数组相同的顺序呈现此组件树。

So how can I dynamically create a component tree based on the components array?那么如何根据 components 数组动态创建组件树呢?

at least one最后一个

Write a recursive function, nest .编写一个递归函数, nest At least one component is required -至少需要一个组件 -

const nest = ([T, ...more]) =>
  more.length == 0
    ? <T />
    : <T>{nest(more)}</T>

Use it in your components like this -像这样在您的组件中使用它 -

function MyComp(props) {
  return nest([A, B, C])
}

possibly zero可能为零

If you want the possibility to support an empty array, this is safest -如果您希望支持空数组,这是最安全的 -

const nest = ([T, ...more]) =>
  T == null
    ? null
    : <T>{nest(more)}</T>
nest([]) // => null
nest([A,B,C]) // => <A><B><C/></B></A>

with props带道具

If you want to supply props to the components, you can use a similar technique -如果您想为组件提供道具,您可以使用类似的技术 -

const nest = ([T, ...more], [p, ...props]) =>
  T == null || p == null
    ? null
    : <T {...p}>{nest(more, props)}</T>
nest([A,B,C], [{active: true}, {onClick: console.log}, {}])
<A active={true}>
  <B onClick={console.log}>
    <C />
  </B>
</A>

alternative选择

If props are needed, a better solution might be to colocate the props with the components using continuations -如果需要道具,更好的解决方案可能是使用延续将道具与组件放在一起 -

const nest = ([T, ...more]) =>
  T == null
    ? null
    : T(nest(more))
nest([ 
  _ => <A active={true}>_</A>,
  _ => <B onClick={console.log}>_</B>,
  _ => <C/>
])
<A active={true}>
  <B onClick={console.log}>
    <C />
  </B>
</A>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM