将表单数据序列化为JSON React

4

我该如何在React中序列化数据?

<form method="post" action="/insert" onSubmit={(e)=>this.addMysql(e)}>
    <label>Username</label>
    <input type="text" id="username" name="nameUser"/>
    <label>Password</label>
    <input type="text" id="password" name="passs"/>
    <button type="submit" type="submit">Dodaj</button>
</form>

这是我的函数。
addMysql(event){
    console.log(event.targe) //this outputs an empty form
    event.preventDefault();
}

我不想使用State。只需在onSubmit时将所有表单数据发送到AddMysql。
谢谢Sag1v。
参考链接:https://medium.com/@snirlugassy/generic-input-handler-with-react-js-44a97e22cd0d

“我不想使用状态(State)” - 那你为什么要使用React呢? - Sagiv b.g
你知道我怎么做才能让这个代码生效吗?setStateVal(e){ this.setState({ [e.target.name]: e.target.value }) }我不想为每个输入框编写一个函数来改变状态,我想通过一个函数来处理所有的输入框。 - Paweł Baca
1
类似于这个 - Sagiv b.g
把这个工作完成,谢谢。 - Paweł Baca
2个回答

1

我建议你使用states,因为这是Reacty的方式。如果不行,我可以提供一些建议。

通常我会建议使用FormData API,但它不受IE和旧版浏览器支持。

我认为这个答案应该能帮到你,因为它是serialize的纯JS版本。

最后,如果你在使用jQuery,可以使用serialize,但我想你可能没有或者不应该使用它。


-1
//So, here's a simple trick i use to get this done:
//Using React Hook

    

const [data, setData] = useState({});
//the create an onInputChange function for the Inputs this way
const onInputChange = async e =>{
  const {name, value} = e.target;
  //check to validate if entry is not a number
  if(isNaN(name)){
    data[name] = value;
    
    //somehow update data
    setData({...data})
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接