javascript 如何在 JSX 中的 React 中循环一个数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47287177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 07:17:24  来源:igfitidea点击:

How to loop over a number in React inside JSX

javascriptreactjs

提问by Taylor Austin

I need to be able to loop over a number and return some jsx. For example

我需要能够遍历一个数字并返回一些 jsx。例如

<ul>
 {for(i =0; i < 10; i++){
   return <li>{i}</li>
 }}
</ul>

This is not exactly what I want to do, but if I can solve this then I should be able to complete what I need to do. This however returns expression expected on the for. I have done some research and people say you can't use forloops inside of jsx because they do not return anything.

这不完全是我想要做的,但如果我能解决这个问题,那么我应该能够完成我需要做的事情。然而,这会返回for. 我做了一些研究,人们说你不能for在 jsx 内部使用循环,因为它们不返回任何东西。

How do I go about looping over a number to return some amount of jsx?

如何遍历一个数字以返回一定数量的 jsx?

回答by Nenad Vracar

You could use Array.from()instead.

你可以用Array.from()

let App = () => {
  return <ul>{Array.from(Array(10), (e, i) => {
    return <li key={i}>{i}</li>
  })}</ul>
}

ReactDOM.render(
  <App />,
  document.getElementById('app')
);
<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
<div id="app"></div>

You can also use ES6 spread syntax with map()method.

您还可以将 ES6 扩展语法与map()方法一起使用。

let App = () => {
  return <ul>{[...Array(10)].map((e, i) => {
    return <li key={i}>{i}</li>
  })}</ul>
}

ReactDOM.render(
  <App />,
  document.getElementById('app')
);
<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
<div id="app"></div>

回答by Vivek Doshi

You can do it like this :

你可以这样做:

createElements(n){
    var elements = [];
    for(i =0; i < n; i++){
        elements.push(<li>{i}</li>);
    }
    return elements;
}

<ul>
    {this.createElements(20)}
</ul>

回答by Robbie Milejczak

You need to use recursive iterators such as map, forEach, filter etc. If you really need to do something like this you can

你需要使用递归迭代器,比如 map、forEach、filter 等。如果你真的需要做这样的事情,你可以

const statelessComp = props => {
    let arr = Array.apply(null, {length: 10}).map(Number.call, Number);
    return (    
        <ul>
            {arr.map(item => {
                return <li>{item}</li> 
            })}
        </ul>
    )
}

edit: these are the functions you should familiarize yourself with

编辑:这些是您应该熟悉的功能