【问题标题】:Loop over Array of Components and render them?循环组件数组并渲染它们?
【发布时间】:2020-12-16 17:03:39
【问题描述】:

似乎是一个有趣的编程问题。

假设你像这样制作一些styled-components

const foo = styled.div`
   font-size: 1rem
`
const bar = styled.div`
   font-size: 2rem
`

然后创建一个array

const styledArr = [ foo, bar ];

你将如何解决这个问题来渲染组件并使用数组循环传递道具?

class App extends React.Component<IAppProps> {
   render() {
      return <>
          // This is not a thing?
          {styledArr.map(a => {
              <a {...this.props['a']} />
          }}
      </>
   }
}

通常你会这样做,但效率较低:

class App extends React.Component<IAppProps> {
   render() {
      return <>
          <Foo {...this.props.foo} />
          <Bar {...this.props.bar />
      </>
   }
}

【问题讨论】:

  • 什么不是东西?您只需要一个大写名称并从映射函数.map(Cmp =&gt; &lt;Cmp {... } /&gt;) 返回
  • @YuryTarabanko:facepalm:谢谢,这很容易。当它编译时,它会识别道具&lt;Cmp {...this.props.Cmp} /&gt;属于接口属性Foo或Bar吗?
  • 我猜你可以使用this.props[Cmp.name],但不确定 TS 是否会对此感到高兴
  • @YuryTarabanko console.log(this.props[Cmp.name]) 返回未定义。 this.props 有效,但我将如何获取组件 Cmp 的当前索引名称以返回 this.props.Foo
  • 我明白了。如果您出于某种原因仍然希望使用这种方法,则需要以某种方式指定名称。例如将其设为const styledArr = [ {name: 'foo', Component: foo }, {name: 'bar', Component: bar } ];,然后设为styledArr.map(({Component, name}) =&gt; &lt;Component {...this.props[name]}/&gt;)

标签: arrays reactjs typescript styled-components


【解决方案1】:

几乎拥有它。您需要解决两件事:

  1. 自定义 JSX 组件必须以大写字母开头。这告诉 JSX 渲染一个组件,而不是原始 HTML。

  2. 你传递给map()的函数必须return每个渲染的组件。您的函数没有返回值,因为您将 {} 用于没有返回语句的函数体。

{styledArr.map(Component => {
    return <Component {...this.props['a']} />
})}

或者使用不带`{}的箭头函数隐式返回组件:

{styledArr.map(Component => <Component {...this.props['a']} />)}

但是,将不同的 props 传递给该数组中的不同组件比较棘手,因为没有一种简单的方法可以将数组索引 0 映射到 this.props.foo 处的 props。如果你需要这样做,我认为这些项目根本不应该是一个数组,你应该一次显式地渲染它们。

【讨论】:

  • 感谢您的解释!如果您可以将this.props[nameof(Component)] 之类的道具传递给foobar,那还是很棒的
猜你喜欢
  • 2018-07-09
  • 1970-01-01
  • 1970-01-01
  • 2018-08-08
  • 1970-01-01
  • 2019-01-07
  • 2018-06-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多