如何映射具有未知嵌套级别的数组? [英] How to map an array with unknown nesting levels?

查看:42
本文介绍了如何映射具有未知嵌套级别的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个注释数组可以有答案,所以数组的每个元素(注释)都可以有嵌套元素(注释),嵌套级别未知,但我需要在 ReactJs 中渲染这个数组来显示这些注释具有给定的嵌套级别.

comment 1-- 评论 2-- 评论 3---- 评论 4-- 评论 5评论 6-- 评论 7

类似的东西.但我不知道该怎么做.

我想看一个如何使用 ReactJs 呈现它的示例,但是如何在 JavaScript 中映射此类数组的示例也会有所帮助.

我的数组比字符串数组更复杂,但让我们想象一下

<预><代码>[{价值":真棒",注释": [{价值":谢谢"评论":空},{"value": "真棒",注释": ["value": "再次感谢",评论":空]}]}]

我希望这个例子会有所帮助.

解决方案

您将使用递归函数.递归意味着函数调用自身,或者在 React 的情况下,调用一个将自身作为子项返回的组件.

这是一个将值呈现为段落元素,然后呈现子评论的示例.

function Comment(props) {返回 (<><p>{props.value}</p>{道具.评论?props.comments.map(comment => {return <Comment comments={comment.comments}/>}): 空值}</>)}

I have an array of comments which can have answers, so every element (comment) of the array can have nested elements (comments) and the nesting level is unknown, but I need to render this array in ReactJs to display these comments with the given nesting level.

comment 1
-- comment 2
-- comment 3
---- comment 4
-- comment 5
comment 6
-- comment 7

Something like this. But I have no idea how to do this.

I would like to see an example how to render it with ReactJs, but an example how to map such arrays in JavaScript would be helpful as well.

My array is more complex then an array of strings, but let's imagine that this is like

[
  {
    "value": "awesome",
    "comments": [
      {
        "value": "thanks"
        "comments": null
      },
      {
        "value": "really awesome",
        "comments": [
          "value": "thanks again",
          "comments": null
        ]
      }
    ]
  }
]

I hope this example will help.

解决方案

You would use a recursive function. Recursive means that the function calls itself, or in the case of React, a component that returns itself as a child.

Here is an example which renders the value as a paragraph element, and then renders the child comments.

function Comment(props) {
    return (<>
        <p>{props.value}</p>
        {props.comments ? 
            props.comments.map(comment => {
                return <Comment comments={comment.comments} />
            })
        : null}
    </>)
}

这篇关于如何映射具有未知嵌套级别的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆