【问题标题】:How to loop inside return statement in javascript如何在javascript中的return语句内循环
【发布时间】:2020-08-20 07:05:03
【问题描述】:

在 jsx 中的原生反应中,我想要一个函数返回这样的循环,我正在这样做,但我的代码在这种情况下说无法访问。

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

【问题讨论】:

标签: javascript reactjs react-native jsx


【解决方案1】:

你只能渲染一个 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>
  );
};

【讨论】:

  • 我需要 for 循环,因为我需要在我的条件下使用属性 for-in 也像 for(var i in array){}
【解决方案2】:

使用地图而不是循环。

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

【讨论】:

    【解决方案3】:

    许多解决方案:

    1. 编写 5x Hello world

    // 函数

    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>
    

    【讨论】:

      猜你喜欢
      • 2017-12-24
      • 2011-08-17
      • 2014-08-28
      • 2021-01-11
      • 2017-11-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多