简体   繁体   中英

How to loop inside return statement in javascript

In react native in jsx i want a function to return a loop like these, I am doing like this but my code is saying unreachable in this case.

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

You can only render a React element.

Here is a simple example, although for loops are barely used.

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>
  );
};

use map instead of loop.

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

Many solutions:

  1. Writing 5x Hello world

// Function

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

// Render

<View>
    {this.getList()}
</View>
  1. Mapping an array of values

// Array

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."
]

// Render

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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