首页 > 解决方案 > React - how to render multiple buttons with a regular for loop?

问题描述

Sorry if its very basic but: when rendering multiple buttons (0-9) in an iteration - What is the difference btw map and for loop ? Why does the for loop only renders the first element (0) while map works fine? Why do I have to first push the buttons into an array and return that then (as seen on other examples) ? Can I use regular for loop and render buttons without pushing it into an arary? Thanks!

 import React from 'react';

    const Keys = () => {        
       const renderKeys = () => {
         //works fine
          var arr = [1,2,3,4,5,6,7,8,9]
          return arr.map((val) => {
              return <button>{val}</button>
            })                 
        };

        const renderKeys = () => {       
              //does not work    
              for (var i=0; i<10; i++) {
               return <button>{i}</button>
            }
        };

        return (
            <div>
                {renderKeys()}
            </div>
        )
    };

标签: reactjs

解决方案


当您return在 for 循环中调用时,它会停止执行循环。这就是为什么你只取回第一个按钮。

return但是,在 a 内部调用.map()不会停止循环的迭代。相反,您使用return明确定义您想要在新数组中拥有的内容。

请注意,.map()通过使用现有数组中的元素创建一个全新的数组。您可以随意使用这些元素,使其适合渲染 JSX。

例子:

const numbers = [1, 2, 3, 4, 5]
const numbersMultipledByTwo = numbers.map((number) => {
   return <div>{ number * 2 }</div>
})

从理论上讲,您可以使用 for 循环实现相同的效果,但这也需要第二个数组的帮助。

工作代码:

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class App extends React.Component{
  getButtonsUsingMap = () => {
    const array = [1, 2, 3 ,4, 5]

    return array.map((number) => {
      return <button>{number}</button>
    })

  }

  getButtonsUsingForLoop = (num) => {
    const array = []

    for(var i = 1; i <= num; i++){
      array.push(<button>{i}</button>)
    }

    return array
  }

  render(){
    return(
      <div>
        <h4>Using .map()</h4>
        {this.getButtonsUsingMap()}
        <h4>using for-loop</h4>
        {this.getButtonsUsingForLoop(5)}
      </div>
    )
  }
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

在该getButtonsUsingForLoop 功能中,您可以看到使其工作的更明确的要求。首先,我们需要满足论点。然后初始化一个新数组。然后为循环定义一个边界。迭代并将 JSX 推送到空数组。然后最终返回该数组。所以逻辑不是很简洁。

而另一方面,a.map()基本上可以处理所有这些。只要你有一个预先存在的数组来迭代(99% 的时间你将处理某种状态或道具数组。)

见沙箱:https ://codesandbox.io/s/pensive-leftpad-lt5ml


推荐阅读