简体   繁体   English

我应该在 ReactJS 中使用 for 循环吗? 当输入更改时,还有其他方法可以同时更改多个元素吗?

[英]Should I use for loops in ReactJS? Any other way to change multiple elements at once when an Input changes?

I'm creating a POS system with ReactJS.我正在用 ReactJS 创建一个 POS 系统。 Should I use a for loop to calculate the total amount?我应该使用 for 循环来计算总量吗? Is there any other way to do this?有没有其他方法可以做到这一点?

let product = testProducts;
let subtotalEl = document.getElementsByClassName("Subtotal");
let quantity = document.getElementsByClassName("Quantity");
for (var i = 0; i < product.length; i++) {
  subtotalEl[i].innerHTML = product[i].UnitPrice * quantity[i].value;
}
  1. You are not using react js, your code looks like JavaScript.你没有使用 react js,你的代码看起来像 JavaScript。
  2. Yes, you can use a loop to add, but in React it is recommended to use map for iterations.是的,您可以使用循环添加,但在 React 中建议使用map进行迭代。

For example:例如:

const sum = array_object
  .map((item) => item.quantity)
  .reduce((prev, curr) => prev + curr, 1);

As you can see, map was used to go through the array, and reduce to add the values.如您所见, map用于遍历数组,并使用reduce来添加值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当我使用任何handleClick时,其他handleClicks会触发 - ReactJS When I use any handleClick, other handleClicks fire 如何将多个引用用于带有钩子的嵌套元素数组或任何其他方式 - How can I use multiple refs for nested arrays of elements with hooks, or any other way 使用bind时,有什么方法可以更改对Javascript函数的调用? - Is there any way I should change my call to a Javascript function when I use bind? 有没有更好的方法一次隐藏多个元素? - Any better way to hide multiple elements at once? 当输入字段中的文本更改时,应使用什么用户输入来触发功能? - What user input should I use for triggering a function when text inside the input field changes? 一次绑定到多个元素上的事件时是否有任何性能提升? - Any performance gain when binding to event on multiple elements at once? 当 api 由于 prop 更改需要多次调用时,应该使用哪个 ReactJS 生命周期 function? - Which ReactJS lifecycle function should be used when an api needs to called more than once due to a prop change? 如何使用jQuery / JavaScript检测多组单选按钮更改并更改单独的表单输入? - How do I use jQuery/JavaScript to detect multiple sets of radio button changes and change a separate form input? 当我使用jquery更改dom中的元素时,我应该真正担心多少 - How much I should really worry when I use jquery to change elements in dom 如何使用按钮在按下一次时更改背景颜色,再次按下时它应保留为 HTML 中的原始颜色? - How do I use a button to change background color when pressed once and when pressed again it should retain to original color in HTML?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM