我的网页中有静态信息。
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>
);
}
}
此页面静态显示在行列表中,每行最多显示三个图标,现在我想动态地将它们旋转,假设我将图标道具存储在props数组中。
[
{
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>
);
}
}
如何通过现实的反应代码做到这一点?
最佳答案
我认为您在问如何确保使用LeftButton
,CenterButton
和RightButton
将图标分为三个组。
我假设您从这样的事情开始:
var icons = [
{
icon: 'MyIcon1',
color: '#ffffff',
text: 'text1'
},
{
icon: 'MyIcon2',
color: '#eeeeee',
text: 'text2'
},
{
icon: 'MyIcon3',
color: '#dddddd',
text: 'text3'
},
{
icon: 'MyIcon4',
color: '#cccccc',
text: 'text4'
}
];
然后,查看评论:
class MyStaticWebPage extends React.Component {
var buttonTypes = [LeftButton, CenterButton, RightButton];
render() {
var rows = [];
var children = [];
for (var i = 0; i < icons.length; i++) {
// x will be 0, 1, or 2
var x = i % 3;
// Get the button type to use
var buttonType = buttonTypes[x];
// Create the button using `createElement`
children.push(React.createElement(buttonType, icons[i]);
// If this is the last button of three, add these in a container
// and get a new array for children
if (x == 2) {
rows.push(<IconContainer>{children}</IconContianer>);
children = [];
}
}
// Handle any remaining children
if (children.length) {
rows.push(<IconContainer>{children}</IconContianer>);
}
return (
<TopContainer>
{rows}
</TopContainer>
);
}
}
关于javascript - 渲染在有条件的for循环中进行 react ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52362936/