首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将来自用户的使用html input标签的输入保存到React JS中的"state“中的数组中。

如何将来自用户的使用html input标签的输入保存到React JS中的"state“中的数组中。
EN

Stack Overflow用户
提问于 2021-09-16 09:57:45
回答 3查看 40关注 0票数 0

我正在尝试将用户使用input标记给出的输入保存到状态中的数组中。我的App.js看起来像这样

代码语言:javascript
复制
class App extends Component {
  
  state = {
    generalInfo: [
      {
        email : "",
        name: "",
        contactNumber: "",
      }
    ],
  }

 handleGeneralSubmit = (e) => {
    e.preventDefault();

    console.log("general submit clicked");   //this function should contain code to take input and store.
  }


 render() { 
    return ( 
      <div>
        <GeneralInfo onGeneralSubmit={this.handleGeneralSubmit} onGeneralEdit={this.handleGeneralEdit} />
      </div>
     );
  }
}
 
export default App;


--------------------
another file generalinfo.jsx


class GeneralInfo extends Component {
  render() {
    const { onGeneralSubmit, onGeneralEdit } = this.props;

    return (
      <div>
   
        <form>
          <div className="form-group m-4">
            <label htmlFor="InputEmail1">Email address</label>
            <input
              type="email"
              className="form-control"
              id="InputEmail1"
              aria-describedby="emailHelp"
              placeholder="Enter email"
            />
            <small id="emailHelp" className="form-text text-muted">
              We'll never share your email with anyone else.
            </small>
          </div>
          <div className="form-group m-4">
            <label htmlFor="inputAddress">Name :</label>
            <input
              type="text"
              className="form-control"
              id="inputName"
              placeholder="Full Name"
            />
          </div>
          <div className="form-group m-4">
            <label htmlFor="inputAddress">Phone Number :</label>
            <input
              type="text"
              className="form-control"
              id="inputContactNumber"
              placeholder="Contact Number"
            />
          </div>
          <button
            onClick={onGeneralSubmit}
            type="submit"
            className="btn btn-primary m-4"
          >
            Submit
          </button>
          <button
            onClick={onGeneralEdit}
            type="submit"
            className="btn btn-warning m-4 "
             //disabled={this.props.generalInfo.length === 0 ? "disabled" : " "}
          >
            Edit
          </button>
        </form>
      </div>
    );
  }
}

export default GeneralInfo;

有人能帮我解决这个问题吗?我对处理状态还很陌生。我不知道函数中到底应该是什么代码。我尝试将e.target.value添加到状态,但它显示错误。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2021-09-16 10:38:10

GeneralInfo实际上应该维护自己的表单状态,然后仅当单击按钮时,才将表单数据作为对象传递给父级。然后可以将其添加到主数组中。

我在这里使用了更现代的React方法:函数组件和useState,但我希望您能理解这是怎么回事。

代码语言:javascript
复制
const { useEffect, useState } = React;

// We accept a submit function in the component props
function GeneralInfo({ submit }) {

  const initialState = { email: '', name: '', number: '' };

  // Initialise the state
  const [ form, setForm ] = useState(initialState);
 
  // When any of the inputs change get the
  // value and name, and use those variables to
  // update the form object in state
  function handleChange(e) {
    const { value, name } = e.target;
    setForm({ ...form, [name]: value });
  }
 
  // When the button is called call the
  // `handleSubmit` function passed in with props
  function handleSubmit() {
    submit(form);
  }
 
  return (
    <div onChange={handleChange}>
      <label>Email: <input name="email" type="email" /></label>
      <label>Name: <input name="name" type="text" /></label>
      <label>Number: <input name="number" type="tel" /></label>
      <button onClick={handleSubmit}>Submit</button>
    </div>
  );

}

function Example() {

  const [ data, setData ] = useState([]);

  // Once the function is called with the form
  // object, update the state with it.
  function handleSubmit(obj) {
    setData([...data, obj]);
  }

  // Here I'm just using `useEffect` to watch
  // for changes in state and logging the result
  useEffect(() => {
    if (data.length) console.log(data);
  }, [data]);

  return (
    <GeneralInfo submit={handleSubmit} />
  );

};

// Render it
ReactDOM.render(
  <Example />,
  document.getElementById("react")
);
代码语言:javascript
复制
label {display: block;}
代码语言:javascript
复制
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>

票数 0
EN

Stack Overflow用户

发布于 2021-09-16 10:07:44

代码语言:javascript
复制
class App extends Component {
  state = {
    generalInfo: [
      {
        email : "",
        name: "",
        contactNumber: "",
      }
    ],
  }

 handleGeneralSubmit = (e, label) => {
    e.preventDefault();

    console.log("general submit clicked");  
    let prevState = this.state;
    prevState.generalInfo[0][label] = e.target.value;
    console.log(prevState)  // to see the new value
    this.setState(prevState);
  }


 render() { 
    return ( 
      <div>
        <GeneralInfo onGeneralSubmit={this.handleGeneralSubmit} onGeneralEdit={this.handleGeneralEdit} />
      </div>
     );
  }
}
 
export default App;


--------------------
another file generalinfo.jsx


class GeneralInfo extends Component {
  render() {
    const { onGeneralSubmit, onGeneralEdit } = this.props;

    return (
      <div>
   
        <form>
          <div className="form-group m-4">
            <label htmlFor="InputEmail1">Email address</label>
            <input
              type="email"
              className="form-control"
              id="InputEmail1"
              aria-describedby="emailHelp"
              placeholder="Enter email"
              onChange={(e)=>onGeneralEdit(e, 'email')}
            />
            <small id="emailHelp" className="form-text text-muted">
              We'll never share your email with anyone else.
            </small>
          </div>
          <div className="form-group m-4">
            <label htmlFor="inputAddress">Name :</label>
            <input
              type="text"
              className="form-control"
              id="inputName"
              placeholder="Full Name"
            onChange={(e)=>onGeneralEdit(e, 'name')}
            />
          </div>
          <div className="form-group m-4">
            <label htmlFor="inputAddress">Phone Number :</label>
            <input
              type="text"
              className="form-control"
              id="inputContactNumber"
              placeholder="Contact Number"
              onChange={(e)=>onGeneralEdit(e, 'contactNumber')}

            />
          </div>
          <button
            onClick={onGeneralSubmit}
            type="submit"
            className="btn btn-primary m-4"
          >
            Submit
          </button>
        </form>
      </div>
    );
  }
}

export default GeneralInfo;

不需要额外的编辑按钮在文本框中输入值,它将更新父组件中的状态

但是我不明白为什么你需要数组中的值,

票数 1
EN

Stack Overflow用户

发布于 2021-09-16 10:27:07

首先,在React中,您应该创建一个状态来存储每个输入值,然后在Input的onChange属性上更改它。您可以在此处查看示例:https://codesandbox.io/s/ecstatic-cdn-lcmes?file=/src/App.js

现在,在状态中存储值之后,可以创建要添加到数组中的值的对象。您应该将其放在名为handleGeneralSubmit的函数中。

它应该看起来像这样:

代码语言:javascript
复制
handleGeneralSubmit = (e) => {
  e.preventDefault(); 
  this.setState(({generalInfo, email, name, contactNumber}) => {
      generalInfo: [...generalInfo, { email, name, contactNumber }]
  })
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69206305

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档