【问题标题】:Getting highest value from one of many inputs从众多输入之一中获得最高价值
【发布时间】:2019-06-14 18:29:58
【问题描述】:

所以我有一个简单的输入字段:

<Input type="number" defaultValue="1" className="quantity"></Input>

但它是由 React 渲染为 12 个不同的 DOM 元素。我需要从每个输入元素中获取值,或者如果可能的话,只获取最高值而不获取每个值。我正在尝试这个:

var amount = document.getElementsByClassName('quantity')

但它输出“未定义”。你们能帮忙吗?

【问题讨论】:

  • 通常在 React 中你不会使用诸如 document.getElementsByClassName() 这样的 DOM 操作。相反,如果您使用 Array.prototype.map() 从数组中渲染这 12 个输入并跟踪组件状态中的每个值,您将使用状态值来查找最高值。您需要分享更多关于如何渲染组件以及如何将每个输入的值存储在 state/store/etc 中的信息。
  • 如果你将值绑定到某个状态,你可以使用Math.max(...someArray),但由于你甚至没有 onChange 我不认为你是did it correctly。您是否按 F12 并在控制台中看到警告?
  • var amount = document.getElementsByClassName('quantity') 会将amount 设置为具有该类的所有元素的 NodeList。不是他们的数量。
  • 可以使用Math.max()
  • 试试document.querySelectorAll

标签: javascript html reactjs


【解决方案1】:

document.getElementsByClassName('quantity') 仅在您的输入具有类属性时才有效。 &lt;input class="quantity"&gt; 它有一个 className 属性。

你想要得到所有输入的是

document.querySelectorAll('[className~="quantity"]')

【讨论】:

  • 由于 class 是 JavaScript 中的保留关键字,React 使用 className 允许您创建 css 类
【解决方案2】:

试试这个:

const maxValue = Math.max(...(Array.from(document.querySelectorAll('.quantity')).map(el => parseInt(el.value, 10))));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-17
    • 2018-05-07
    相关资源
    最近更新 更多