本文介绍了为什么在使用create-react-app时表单未提交?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我迁移到使用create-react-app之前,我的google auth按钮工作正常。当我切换到CRA时,该表单未提交到服务器,相反,该应用似乎将 action 属性中的新路径推送到了历史记录。 CRA是否会自动以某种方式禁用表单提交?周围有工作吗?谢谢!

My google auth button was working fine before I migrated to using create-react-app. when I switch to CRA, the form is not being submitted to the server and instead it seems like the app is pushing the new path in the action attribute to the history. Does CRA automatically disables form submission somehow? is there a work around? Thanks!

这是表格:

<form method="get" action="/aoth/google" className="google-form">
      <input type="submit" className="google-login" value="Google+" />
</form>


推荐答案

下面是一个简单的代码段,显示了如何处理表单提交。希望有帮助。

Here's a simple snippet showing how to handle form submission. Hope that helps.

class App extends React.Component {
  constructor() {
    super();
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(event) {
    event.preventDefault();
    const form = event.target;
    const data = new FormData(form);
    for (let name of data.keys()) {
      const input = form.elements[name];
      console.log(input);
      console.log(input.value);
    }

    fetch('/aoth/google', {
      method: 'GET',
      body: data,
    });
  }

    render() {
      return (
        <form onSubmit={this.handleSubmit} className="google-form">
              <input id="username" name="username" type="text" />
              <input type="submit" className="google-login" value="Google+" />
        </form>
      );
   }
}

ReactDOM.render( < App / > ,
  document.getElementById('root')
)
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>

<div id="root" />

这篇关于为什么在使用create-react-app时表单未提交?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 03:07