reactjs - 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>
)
};
解决方案
当您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% 的时间你将处理某种状态或道具数组。)
推荐阅读
- javascript - 在 Chrome 网络蓝牙 API 中未经用户许可连接到配对设备?
- c# - 等待和信号功能
- sql - SQL SERVER 更新并插入到具有重复值的不同表中
- javascript - 将对象数组克隆到自身中
- node.js - npm 配置设置注册表
- 我们可以使用注册表指向本地 node_modules 文件夹吗 - linux - 无密码启动 systemd 服务
- angular - 订阅主题时双重请求
- php - 在 php/wordpress 中删除带有特殊字符的子字符串
- docker - 如何构建 docker 镜像文件并推送 Vsts
- powershell - Azure RM Powershell 中的 storageAccount 不支持 API 版本 - 没有注册的资源提供程序