【发布时间】: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 => <Cmp {... } />)返回 -
@YuryTarabanko:facepalm:谢谢,这很容易。当它编译时,它会识别道具
<Cmp {...this.props.Cmp} />属于接口属性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}) => <Component {...this.props[name]}/>)
标签: arrays reactjs typescript styled-components