簡體   English   中英

如何在 javascript 中循環返回語句

[英]How to loop inside return statement in javascript

在 jsx 中的本機反應中,我希望 function 返回這樣的循環,我正在這樣做,但我的代碼在這種情況下說無法訪問。

<View>
  {()=>{
   return ( for(var i=0;i<5;i++){
               <Text>Hello World</Text>
          })
   }}
</View>

你只能渲染一個 React 元素。

這是一個簡單的示例,盡管幾乎沒有使用for循環。

let content = [];
for (let i = 0; i < 5; i++) {
  content.push(<h1>Hello World using for loop</h1>);
}

const App = () => {
  return (
    <div>
      {content}
      {[...Array(5).keys()].map((key) => (
        <h1 key={key}>Hello World using map</h1>
      ))}
    </div>
  );
};

使用 map 而不是循環。

Array.from({ length: 5 }).map((v) => <Text key={v}>{v}</Text>)

許多解決方案:

  1. 編寫 5x Hello world

// Function

getList(){
    let texts = []
    for (let index = 0; index < 5; index++) {
        texts.push(<Text>Hello World</Text>)
    }
    return texts
}

// 使成為

<View>
    {this.getList()}
</View>
  1. 映射值數組

// 大批

const list = [
    "Hello World",
    "Ad adipisicing ea ut in officia.",
    "Consectetur ipsum commodo reprehenderit sit est aliquip commodo ad qui duis et exercitation.",
    "Est sint esse veniam laborum cillum ullamco aliquip aute eiusmod cupidatat."
]

// 使成為

<View>
    {list.map((text, index) => <Text key={index}>{text}</Text>)}
</View>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM