Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/380.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在react中清除动态表单的输入值_Javascript_Reactjs - Fatal编程技术网

Javascript 如何在react中清除动态表单的输入值

Javascript 如何在react中清除动态表单的输入值,javascript,reactjs,Javascript,Reactjs,我有一个动态表单作为功能组件,它是通过基于类的组件生成的。我想做一个重置按钮,它清除输入字段值并将状态设置为空数组 完整代码可在此处获得: 我想创建一个重置按钮,清除所有输入值并将Itemvalues数组初始化为null。 即使我将值设置为null,也不会清除输入字段 然而,我面临的问题是,由于它是一个动态表单和一个功能组件,它没有为每个表单字段预定义的状态,因此很难将值设置为null。 有人能帮我一下吗?我很久以来一直在这个问题上挣扎为了控制子组件(项目)的值,我认为这些子组件(项目)是输入

我有一个动态表单作为功能组件,它是通过基于类的组件生成的。我想做一个重置按钮,它清除输入字段值并将状态设置为空数组

完整代码可在此处获得:

我想创建一个重置按钮,清除所有输入值并将Itemvalues数组初始化为null。 即使我将值设置为null,也不会清除输入字段

然而,我面临的问题是,由于它是一个动态表单和一个功能组件,它没有为每个表单字段预定义的状态,因此很难将值设置为null。
有人能帮我一下吗?我很久以来一直在这个问题上挣扎

为了控制子组件(项目)的值,我认为这些子组件(项目)是输入字段,您需要从它们的父组件传递它们的值。因此,您的每个项目都将有一个
item.value
,该值存储在父组件的状态中

这意味着在父组件中,您将能够定义一个方法,该方法将清除它在其状态下存储的所有项值。 那可能看起来像

resetInputs = () => {
    this.setState({
        inputFields: this.state.inputFields.map(inputField => {
            ...inputField,
            value: ''
        }
    })
}
此外,您还需要编写代码工作所需的标记类型,如输入

因此,您共享的子组件的代码的最终结果如下:

const Form = (props) => {
    return (
    <div>
        {props.Items.map(item => (
          <input
            name={item.name}
            value={item.value}
            placeholder={item.description}
            onChange={e => props.onChangeText(e)}
          /> 
        )
        )}
      </div> 
    );
}
export default Form 
const Form=(道具)=>{
返回(
{props.Items.map(item=>(
props.onChangeText(e)}
/> 
)
)}
);
}
导出默认表单

要管理未知数量
N
项的状态,一种方法是管理包含所有状态的单个对象,例如,
setValuesManager
管理
N
输入并单击
按钮
重置其状态:

函数text区域管理器(){
常量[valuesManager,setValuesManager]=useState([…项]);
返回(
{valuesManager.map((值,i)=>(
{
valuesManager[i]=e.target.value;
setValuesManager([…valuesManager]);
}}
/>
))}
setValuesManager([…数组(valuesManager.length).fill(“”)])
}
>
全部重置
);
}
演示:


这里有一个代码沙盒,向您展示如何重置项目:

我还为您留下了一条关于如何使用API数据的注释,请参见
onChangeText()中的注释

问题在于,输入并不像您推断的那样由状态控制。我们应该为API中的每个项目创建一个更新的对象,给它一个
value
prop

index.js 现在,在
表单
组件中,我们为每个输入提供一个连接到最上层父组件状态项的值属性


这就是重置值所需的全部内容

看看这是否适合你:

由于您已经在部分代码中使用了钩子,我已经使用钩子将您的类转换为功能组件(我的建议是:学习钩子,忘记类组件)。

我已将
属性添加到您的
初始状态
,因此它将保留每个
输入项
的输入值

完整代码:

index.js

import React, { useState } from "react";
import ReactDOM from "react-dom";
import FormV2 from "./FormV2";

import "./styles.css";

function App() {
  const INITIAL_STATE = [
    {
      name: "item1",
      description: "item1",
      group: "groupA",
      dtype: "str",
      value: "" // ADDED VALUE PROPERTY TO KEEP THE INPUT VALUE
    },
    {
      name: "item2",
      description: "item2",
      group: "groupA",
      dtype: "str",
      value: ""
    },
    {
      name: "item3",
      description: "item3",
      group: "groupB",
      dtype: "str",
      value: ""
    },
    {
      name: "item4",
      description: "item4",
      group: "groupB",
      dtype: "str",
      value: ""
    }
  ];

  const [inputItems, setInputItems] = useState(INITIAL_STATE);

  function handleChange(event, index) {
    const newValue = event.target.value;
    setInputItems(prevState => {
      const aux = Array.from(prevState);
      aux[index].value = newValue;
      return aux;
    });
  }

  function handleReset() {
    console.log("Reseting Form to INITIAL_STATE ...");
    setInputItems(INITIAL_STATE);
  }

  function handleSubmit() {
    inputItems.forEach(item =>
      console.log(
        "I will submit input: " + item.name + ", which value is: " + item.value
      )
    );
  }

  return (
    <FormV2
      handleSubmit={handleSubmit}
      handleReset={handleReset}
      handleChange={handleChange}
      inputItems={inputItems}
    />
  );
}

ReactDOM.render(<App />, document.getElementById("root"));
import React from "react";

function FormV2(props) {
  const formInputItems = props.inputItems.map((item, index) => (
    <div key={item.name}>
      {item.name + ": "}
      <input
        type="text"
        data-type={item.dtype}
        data-group={item.group}
        placeholder={item.description}
        value={item.value}
        onChange={event => props.handleChange(event, index)}
      />
    </div>
  ));

  return (
    <React.Fragment>
      <form>{formInputItems}</form>
      <button onClick={props.handleSubmit}>Submit</button>
      <button onClick={props.handleReset}>Reset</button>
      <div>State: {JSON.stringify(props.inputItems)}</div>
    </React.Fragment>
  );
}

export default FormV2;
import React,{useState}来自“React”;
从“react dom”导入react dom;
从“/FormV2”导入FormV2;
导入“/styles.css”;
函数App(){
常量初始状态=[
{
名称:“项目1”,
说明:“第1项”,
集团:“集团A”,
数据类型:“str”,
值:“”//添加值属性以保留输入值
},
{
名称:“项目2”,
说明:“项目2”,
集团:“集团A”,
数据类型:“str”,
值:“”
},
{
名称:“项目3”,
说明:“第3项”,
集团:“集团B”,
数据类型:“str”,
值:“”
},
{
名称:“项目4”,
说明:“第4项”,
集团:“集团B”,
数据类型:“str”,
值:“”
}
];
常量[inputItems,setInputItems]=useState(初始状态);
函数句柄更改(事件、索引){
const newValue=event.target.value;
setInputItems(prevState=>{
const aux=Array.from(prevState);
aux[index].value=newValue;
返回aux;
});
}
函数handleReset(){
日志(“将表单重置为初始状态…”);
setInputItems(初始状态);
}
函数handleSubmit(){
inputItems.forEach(项=>
console.log(
我将提交输入:“+item.name+”,其值为:“+item.value”
)
);
}
返回(
);
}
render(,document.getElementById(“根”));
FormV2.js

import React, { useState } from "react";
import ReactDOM from "react-dom";
import FormV2 from "./FormV2";

import "./styles.css";

function App() {
  const INITIAL_STATE = [
    {
      name: "item1",
      description: "item1",
      group: "groupA",
      dtype: "str",
      value: "" // ADDED VALUE PROPERTY TO KEEP THE INPUT VALUE
    },
    {
      name: "item2",
      description: "item2",
      group: "groupA",
      dtype: "str",
      value: ""
    },
    {
      name: "item3",
      description: "item3",
      group: "groupB",
      dtype: "str",
      value: ""
    },
    {
      name: "item4",
      description: "item4",
      group: "groupB",
      dtype: "str",
      value: ""
    }
  ];

  const [inputItems, setInputItems] = useState(INITIAL_STATE);

  function handleChange(event, index) {
    const newValue = event.target.value;
    setInputItems(prevState => {
      const aux = Array.from(prevState);
      aux[index].value = newValue;
      return aux;
    });
  }

  function handleReset() {
    console.log("Reseting Form to INITIAL_STATE ...");
    setInputItems(INITIAL_STATE);
  }

  function handleSubmit() {
    inputItems.forEach(item =>
      console.log(
        "I will submit input: " + item.name + ", which value is: " + item.value
      )
    );
  }

  return (
    <FormV2
      handleSubmit={handleSubmit}
      handleReset={handleReset}
      handleChange={handleChange}
      inputItems={inputItems}
    />
  );
}

ReactDOM.render(<App />, document.getElementById("root"));
import React from "react";

function FormV2(props) {
  const formInputItems = props.inputItems.map((item, index) => (
    <div key={item.name}>
      {item.name + ": "}
      <input
        type="text"
        data-type={item.dtype}
        data-group={item.group}
        placeholder={item.description}
        value={item.value}
        onChange={event => props.handleChange(event, index)}
      />
    </div>
  ));

  return (
    <React.Fragment>
      <form>{formInputItems}</form>
      <button onClick={props.handleSubmit}>Submit</button>
      <button onClick={props.handleReset}>Reset</button>
      <div>State: {JSON.stringify(props.inputItems)}</div>
    </React.Fragment>
  );
}

export default FormV2;
从“React”导入React;
功能表单v2(道具){
const formInputItems=props.inputItems.map((项目,索引)=>(
{item.name+“:”}
props.handleChange(事件、索引)}
/>
));
返回(
{formInputItems}
提交
重置
状态:{JSON.stringify(props.inputItems)}
);
}
导出默认表单v2;

在这种情况下,您能告诉我如何设置父组件中的状态吗?您的意思是当您更改输入字段中的值时?因为它看起来不像您在任何地方定义的onChangeText。您的onChangeText需要是这样的:
onChangeText=(itemIndex,newValue)=>{this.setState({Items:[…this.state.Items.slice(0,itemIndex),{…this.state.Items[itemIndex],value:newValue},…this.state.Items.slice(itemIndex+1)]}
然后在子组件中,您可以这样使用它:
{props.Items.map((item,index)=>(props.onChangeText(index,e.currentTarget.value)}
在我的例子中,我有一个函数填充Items数组,并为每个项生成一个输入字段。因此,我不知道如何访问这些值
import React from "react";

function FormV2(props) {
  const formInputItems = props.inputItems.map((item, index) => (
    <div key={item.name}>
      {item.name + ": "}
      <input
        type="text"
        data-type={item.dtype}
        data-group={item.group}
        placeholder={item.description}
        value={item.value}
        onChange={event => props.handleChange(event, index)}
      />
    </div>
  ));

  return (
    <React.Fragment>
      <form>{formInputItems}</form>
      <button onClick={props.handleSubmit}>Submit</button>
      <button onClick={props.handleReset}>Reset</button>
      <div>State: {JSON.stringify(props.inputItems)}</div>
    </React.Fragment>
  );
}

export default FormV2;