简体   繁体   English

使用打开和关闭标签来反应地图

[英]React map with opening and closing tags

So i want to print a group of nested lists with react components around certain elements. 所以我想在一组围绕某些元素的组件上打印一组嵌套列表。 the array looks like this (with 1 and -1 indicating to move deeper in levels): 数组看起来像这样(带有1和-1表示要更深入地移动级别):

const linkArray = ['value','another value',1,'third value',-1,'fourth value']

which i want to render like 我想渲染像

<ol>
  <li><SomeComponent>value</SomeComponent></li>  
  <li><SomeComponent>another value</SomeComponent></li>
  <ol>
    <li><SomeComponent>third value</SomeComponent></li>
  </ol>
<li><SomeComponent>fourth value</SomeComponent></li>

what i have now is: 我现在所拥有的是:

 <ol>{linkArray.map(link =>{
     if (link == 1) {
       return <ol>;
     } else if (link == -1) {
       return </ol>;
     }
     else
       return <li><SomeComponent>{link}</SomeComponent></li>;
 })}
 </ol>

this won't compile and i'm assuming it's because you can't just include an opening tag without a closing tag in map. 这不会编译,我认为这是因为您不能只在地图中包含没有结束标记的开始标记。

Neither <ol> nor </ol> are valid JSX, which is why your current code fails. <ol></ol>都不是有效的JSX,这就是您当前代码失败的原因。

My advice would be to reshape your data structure such that you are not relying on the 1 and -1 to tell you when to go up or down a level in nesting. 我的建议是重塑数据结构,以使您不必依靠1-1告诉您何时向上或向下嵌套。 Something like this would be easier to work with: 这样的事情将更容易使用:

const linkArray = ['value', 'another value', ['third value'], 'fourth value']

This way, your data structure has the same shape as the desired output. 这样,您的数据结构具有与所需输出相同的形状。

From here, we can define a recursive function, which will render a new <li> element when it encounters a string, and a new <ol> element when it encounters an array: 从这里,我们可以定义一个递归函数,当遇到字符串时,它将呈现一个新的<li>元素,而当遇到一个数组时,将呈现一个新的<ol>元素:

const nestedList = link => {
  if (link instanceof Array) {
    return <ol>{link.map(nestedList)}</ol>;
  } else {
    return <li>{link}</li>;
  }
}

Then return the following in your main component's render method (a call to the function we just defined wrapped in an outer set of <ol> tags): 然后在主要组件的render方法中返回以下内容(对我们刚刚定义的函数的调用包装在一组<ol>标记中):

<ol>{linkArray.map(nestedList)}</ol>

The following HTML is rendered: 呈现以下HTML:

<ol>
  <li>value</li>
  <li>another value</li>
  <ol>
    <li>third value</li>
  </ol>
  <li>fourth value</li>
</ol>

Which is the desired output (minus the <SomeComponent> tags, which I left out for simplicity's sake - they don't affect the logic). 这是所需的输出(减去<SomeComponent>标记,为简单起见,我将其省略了-它们不会影响逻辑)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM