首页 > 解决方案 > 渲染在条件 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>
    );
  }
}

如何通过真实的反应代码来做到这一点?

标签: javascriptreactjs

解决方案


假设您有一个平面数组,但想以三行的形式呈现它,您应该做的第一件事是将数组分块。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>
    );
  }
}

推荐阅读