arrays - 循环组件数组并渲染它们?
问题描述
似乎是一个有趣的编程问题。
假设你做了一些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 />
</>
}
}
解决方案
你几乎拥有它。您需要解决两件事:
自定义 JSX 组件必须以大写字母开头。这告诉 JSX 渲染一个组件,而不是原始 HTML。
您传递给的函数
map()
必须是return
每个渲染的组件。您的函数没有返回值,因为您{}
在没有 return 语句的情况下使用了函数体。
{styledArr.map(Component => {
return <Component {...this.props['a']} />
})}
或者使用不带 `{} 的箭头函数隐式返回组件:
{styledArr.map(Component => <Component {...this.props['a']} />)}
然而,将不同的道具传递给该数组中的不同组件比较棘手,因为没有一种简单的方法可以将数组索引映射0
到this.props.foo
. 如果你需要这样做,我认为这些项目根本不应该是一个数组,你应该一次显式地渲染它们。
推荐阅读
- javascript - 如何更改使用 ttypescript 生成的 typscript 源文件的名称
- c# - 尽管已定义,但缺少关系定义的错误消息
- entity-framework - EF Core 导航属性和映射配置文件
- typescript - 如何让 TypeScript 推断实现泛型接口的对象的具体类型?
- javascript - 如何在 JSX 内的循环内渲染?
- python - 使用 Pandas 将数据从一个工作簿工作表复制到另一个
- spring-boot - 使用 Apache Camel 依赖项升级 Spring Boot 应用程序的问题
- reactjs - 如何在 Typescript 中使用以数字开头的别名
- android - RecyclerView 中未调用 RecyclerAdapter 覆盖方法(OnBindViewHolder 和 onCreateViewHolder)
- github - Ansible 集合 - 重用来自 github 的角色