简体   繁体   English

如何在 React 中使用对象数组渲染组件

[英]How to render components with array of objects in React

To setup my issue: I want to sort a text-document with regions of texts.设置我的问题:我想用文本区域对文本文档进行排序。 the structure of data is:数据结构为:

{"words": ["Horn ", "Cirque ", "Glacier in Longitudinal Section "] }
{"words": ["my other ", "line ", "of texts"] }

inside an array.数组内。 The result must be rendered in React using a webComponent for each sentence:结果必须在 React 中使用 webComponent 为每个句子呈现:

textContent.map((sentences, index) =>
              <article>
               <desc-sentence>{sentences}</desc-sentence>
              </article>

          )

textContent is the variable containing each sentence in regions. textContent是包含区域中每个句子的变量。

but Objects are not valid as Children in react.但对象在儿童反应中无效。 An array is way recommanded, how to pass array with indexes ?建议使用数组,如何传递带索引的数组?

*Edit *编辑

the output shoud be输出应该是

 let textContent = [ {"words": ["Horn ", "Cirque ", "Glacier in Longitudinal Section "]}, {"words": ["V-shaped valley ", "carved by a river "]} ] console.log(textContent[0].words);
 <section> <!-- inside the textContent loop of words--> <article> <p>{sentence}</p> <p>{sentence}</p> </article> <article> <p>{sentence}</p> <p>{sentence}</p> </article> </section>

Here is the same code based on your requirement.You can check the HTML structure I think it's mostly what you want tag has all the names wrapped it in这是基于您的要求的相同代码。您可以检查 HTML 结构我认为这主要是您想要的标签将所有名称都包裹在其中

 import React from 'react' class TestJS extends React.Component { render(){ let textContent = [ {"words": ["Horn ", "Cirque ", "Glacier in Longitudinal Section "]}, {"words": ["V-shaped valley ", "carved by a river "]} ]; let finalStringMessage = []; let textContentLength = textContent.length; for(let i=0; i < textContentLength; i++){ let wordsArray = textContent[i].words; let articleName = wordsArray.map((sentences, index) => <desc-sentence>{sentences}</desc-sentence> ); finalStringMessage.push(<article>{articleName}</article>) } return( <div>{finalStringMessage}</div> ) } } export default TestJS;

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

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