【问题标题】:JAVASCRIPT / REACT: Return HTML for every element in a for loopJAVASCRIPT / REACT:为 for 循环中的每个元素返回 HTML
【发布时间】:2021-04-01 11:32:42
【问题描述】:

我在 stackoverflow 上查看了其他一些答案,但找不到能回答我问题的答案。

我有一个变量 toolShortcuts,它是一个由对象数组组成的对象:

toolShortcuts = {
  1: [{key: "s", description: "click this to scale"}],
  2: [{key: "delete", description: "click this to delete"}, {key: "backspace",description: "click this to delete"}]
}

我正在尝试为对象中的每个元素(上述对象中的 3 个元素)返回一些 HTML。由于我使用带有 return 语句的 for 循环,因此仅显示每个数组的第一个元素(3 个元素中的 2 个)。如何显示所有三个元素?

  <Container>
    { Object.values(toolShortcuts).map((shortcuts) => {
        for (let i in shortcuts) {
          return (
            <Row>
              <$DescriptionCol>{shortcuts[i].description}</$DescriptionCol>
              <$ButtonCol lg="3">{shortcuts[i].key}</$ButtonCol>
            </Row>
          )
        }
      })
    }
  </Container>

【问题讨论】:

  • 请标记您正在使用的模板或框架 - 看起来像 React
  • [key: "s", description: "click this to scale"] 应该是[{key: "s", description: "click this to scale"}]
  • 另外,returnfor 中只是退出循环。您已经在上面使用map,您可以再次使用 map 并且它会起作用。也许在那里扔一个flatMap
  • 这能回答你的问题吗? How do I use for loops with react?
  • 如果要嵌套两个循环,则需要使用flatMap 而不是第一个map。否则,是的,这就是我的意思。

标签: javascript html reactjs loops


【解决方案1】:
<Container>
    {Object.values(toolShortcuts).map((shortcuts, indexTool) => (
        <React.Fragment key={indexTool}>
            {shortcuts.map((shortcut) => (
                <Row key={shortcut.key}>
                    <$DescriptionCol>{shortcut.description}</$DescriptionCol>
                    <$ButtonCol lg="3">{shortcut.key}</$ButtonCol>
                </Row>        
            ))}
        </React.Fragment>
    }
</Container>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-18
    • 1970-01-01
    • 2021-08-24
    • 2020-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多