首页 > 解决方案 > 循环组件数组并渲染它们?

问题描述

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

假设你做了一些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 />
      </>
   }
}

标签: arraysreactjstypescriptstyled-components

解决方案


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

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

  2. 您传递给的函数map()必须是return每个渲染的组件。您的函数没有返回值,因为您{}在没有 return 语句的情况下使用了函数体。

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

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

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

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


推荐阅读