提交表单后如何将用户重定向到另一个页面?

2023-12-25

我想在 React JavaScript 中提交表单后重定向用户,例如当用户提交他/她重定向到的表单时google.com或一些其他 URL,其中包含他/她在输入字段中输入的信息。我创建了一个简单的文件和提交按钮。

这是我的示例代码

import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
class App extends Component {
  state = {
    firstName: '',
    showName: false
  }
  inputHandler = (e) => {
    let updatedName = e.target.value;
    this.setState({ firstName: updatedName });
    //console.log(updatedName);  
  }
  onSubmitHandler = (e) => {
    e.preventDefault();
    this.setState({
      showName: true
    });
  }
  render() {
    return (
      <div>
        <form
          onSubmit={this.onSubmitHandler}>
          <label>Enter the Name</label>
          <input type="text"
            name="firstName" onChange={this.inputHandler} value=
            {this.state.firstName} />
          <button type="submit" onClick={this.onSubmitHandler}>Submit</button>
          {this.state.showName && <p>"FirstName: " {this.state.firstName}</p>}
        </form>
      </div>
    );
  }
}
export default (App);

您可以使用 this.props.history.push 方法进行重定向。

  onSubmitHandler = (e) => {
    e.preventDefault();
   this.props.history.push('/dashboard')
  }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

提交表单后如何将用户重定向到另一个页面? 的相关文章