我有一个注释数组可以有答案,所以数组的每个元素(注释)都可以有嵌套元素(注释),嵌套级别未知,但我需要在 ReactJs 中渲染这个数组来显示这些注释具有给定的嵌套级别.
comment 1-- 评论 2-- 评论 3---- 评论 4-- 评论 5评论 6-- 评论 7类似的东西.但我不知道该怎么做.
我想看一个如何使用 ReactJs 呈现它的示例,但是如何在 JavaScript 中映射此类数组的示例也会有所帮助.
我的数组比字符串数组更复杂,但让我们想象一下
[{价值":真棒",注释": [{价值":谢谢"评论":空},{"value": "真棒",注释": ["value": "再次感谢",评论":空]}]}]我希望这个例子会有所帮助.
解决方案您将使用递归函数.递归意味着函数调用自身,或者在 React 的情况下,调用一个将自身作为子项返回的组件.
这是一个将值呈现为段落元素,然后呈现子评论的示例.
function Comment(props) {返回 (<><p>{props.value}</p>{道具.评论?propsments.map(comment => {return <Comment comments={commentments}/>}): 空值}</>)}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 7Something 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> {propsments ? propsments.map(comment => { return <Comment comments={commentments} /> }) : null} </>) }
更多推荐
如何映射具有未知嵌套级别的数组?
发布评论