javascript - 渲染在条件 for 循环中做出反应
问题描述
我在网页中有一个静态信息。
class MyStaticWebPage extends React.Component {
render() {
return (
<TopContainer>
<IconListContainer>
<LeftButton
Icon={MyIcon1}
color="#ffffff"
text="text1"
/>
<CenterButton
Icon={MyIcon2}
color="#eeeeee"
text="text2"
/>
<RightButton
Icon={MyIcon3}
color="#dddddd"
text="text3"
/>
</IconListContainer>
<IconListContainer>
<LeftButton
Icon={MyIcon4}
color="#cccccc"
text="text4"
/>
</IconListContainer>
</TopContainer>
);
}
}
这个页面静态显示在一个行列表中,每行最多三个图标,现在我想动态转动它们,假设我将图标道具存储在道具数组中。
[
{
icon: 'MyIcon1',
color: '#ffffff',
text: 'text1'
},
{
icon: 'MyIcon2',
color: '#eeeeee',
text: 'text2'
},
{
icon: 'MyIcon3',
color: '#dddddd',
text: 'text3'
},
{
icon: 'MyIcon4',
color: '#cccccc',
text: 'text4'
}
]
最后使用这个 props 数组自动渲染页面。
class MyStaticWebPage extends React.Component {
render() {
var rows = []
for (var i = 0; i <= parseInt(iconNum / 3); i++) {
// row level for loop
// rows.push(row)
for (var j = iconNum; j % 3 !== 0; j--) {
// icon level for loop
// rows.push(icon)
}
}
return (
<TopContainer>
{rows}
</TopContainer>
);
}
}
如何通过真实的反应代码来做到这一点?
解决方案
假设您有一个平面数组,但想以三行的形式呈现它,您应该做的第一件事是将数组分块。Lodash 有一个方法可以解决这个问题,或者你可以在你的数组上做一个足够简单的 reduce。
const chunkedArray = icons.reduce((reduction, icon, index) => {
index % 3 ? reduction[reduction.length - 1].push(icon) : reduction.push([icon])
return reduction
}, [])
现在您的数据具有正确的形状,我们可以轻松地将其映射到输出 jsx。
class IconListWrapper extends React.Component {
render() {
const { subList } = this.props
const buttonTypes = ['LeftButton', 'CenterButton', 'RightButton']
const Element = buttonTypes[index]
return (
<IconListContainer>
{subList.map((icon, index) => <Element
Icon={MyIcon1}
color="#ffffff"
text="text1"
/>)}
</IconListContainer>
);
}
}
class MyStaticWebPage extends React.Component {
render() {
return (
<TopContainer>
{chunkedArray.map((subList) => <IconListWrapper subList={subList} />)}
</TopContainer>
);
}
}
推荐阅读
- git - zsh 上的 git 完成未列出不明确的选项(在 macOS 上)
- css - 在 Div 中堆叠图像和文本,允许文本控制 Div 中的高度
- nfc - 发送数据、使用 HCE 还是使用安全元件?(Android、Kotlin、Mifare 1k)
- linux - GCP 紧急模式不可用 fs '/' 处于只读状态
- android - 如何在第一个活动中更新回收站视图,同时更改其他活动中的数据?
- progress - 制表符显示来自不同数据字段的进度图例编号
- haskell - 为什么编译器不能在 Haskell 中为我们处理 newtype?
- maven - 来自私有包注册表的 Gitlab CI/CD Maven 依赖项:找不到工件
- html - Bootstrap - 2列 - 在窄屏幕上使图像全宽
- sql - 解析两个字符之间的单词 SQL Netezza