react循环对输入框赋值 您所在的位置:网站首页 react动态给input赋值 react循环对输入框赋值

react循环对输入框赋值

2023-10-08 12:52| 来源: 网络整理| 查看: 265

react循环对输入框赋值

There's a lot to consider when working on a React application, especially when they involve forms. Even if you're able to create a submit button and update your app's state the way you want, clearing the forms can be difficult.

在React应用程序上工作时,要考虑很多事情,尤其是当它们涉及表单时。 即使您能够创建一个提交按钮并以所需的方式更新应用程序的状态,清除表单也可能很困难。

Say your application has dynamic forms like this:

假设您的应用程序具有以下动态形式:

And simple input boxes are rendered to the page:

并将简单的输入框呈现到页面:

When a user enters text into one of the input boxes, it's saved to the application state in groups like this:

当用户在其中一个输入框中输入文本时,它将以如下组的形式保存到应用程序状态:

Itemvalues: 0: groupA: item1: itemvalue1 item2: itemvalue2 groupB: item3: itemvalue3 item4: itemvalue4

It's pretty complicated, but you managed to get that working.

这很复杂,但是您设法使它起作用。

In handleReset, you're able to set itemvalues back to a null state when the "Reset" button is pressed:

在handleReset ,当按下“重置”按钮时,您可以将itemvalues设置回空状态:

handleReset = () => { this.setState({ itemvalues: [{}] }); };

But the problem is that the text is not cleared from all of the input boxes:

但是问题在于,并未从所有输入框中清除文本:

You've already handled storing the actual text in the state, so here's a simple way to clear the text from all input boxes.

您已经处理了将实际文本存储在状态中的操作,因此这是一种从所有输入框中清除文本的简单方法。

如何清除所有输入的值 (How to clear the values all inputs)

At the top of handleReset, use document.querySelectorAll('input') to select all the input elements on the page:

在handleReset的顶部,使用document.querySelectorAll('input')选择页面上的所有输入元素:

handleReset = () => { document.querySelectorAll('input'); this.setState({ itemvalues: [{}] }); };

document.querySelectorAll('input') returns a NodeList, which is a bit different than an array, so you can't use any useful array methods on it.

document.querySelectorAll('input')返回一个NodeList ,它与数组有些不同,因此您不能在其上使用任何有用的数组方法。

To turn it into an array, pass document.querySelectorAll('input') to Array.from():

要将其转换为数组,请将document.querySelectorAll('input')传递给Array.from() :

handleReset = () => { Array.from(document.querySelectorAll('input')); this.setState({ itemvalues: [{}] }); };

Now all you have to do is iterate through each of the inputs and set its value attribute to an empty string. The forEach method is a good candidate for this:

现在,您要做的就是遍历每个输入并将其value属性设置为一个空字符串。 forEach方法是一个很好的选择:

handleReset = () => { Array.from(document.querySelectorAll("input")).forEach( input => (input.value = "") ); this.setState({ itemvalues: [{}] }); };

Now when a user presses the "Reset" button, the value of every input is cleared, too:

现在,当用户按下“重置”按钮时,每个输入的值也将被清除:

翻译自: https://www.freecodecamp.org/news/how-to-clear-input-values-of-dynamic-form-in-react/

react循环对输入框赋值



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有