在React JS中提交表单后,如何将用户重定向到另一个页面

时间:2018-10-19 07:39:11

标签: javascript reactjs

在react js中提交表单后,我想重定向用户,例如当用户提交表单时,他/她重定向到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);

预先感谢

3 个答案:

答案 0 :(得分:0)

onSubmitHandler = (e) => {
    e.preventDefault();
    this.setState({
      showName: true
    });
    window.location.href = "someurl/somepage?var1="+this.state.var1+"&var2="+this.state.var2 + "......";
  }

答案 1 :(得分:0)

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

  onSubmitHandler = (e) => {
    e.preventDefault();
   this.props.history.push('/dashboard')
  }

答案 2 :(得分:0)

Checking(event) {
event.preventDefault();
if (this.state.username === "" || this.state.password === "") {
  alert("Fields are required");
  return;
}
if (this.state.username == "subrata" && this.state.password === "1234") {
  this.props.history.push('/adminpanel')
  return;
}else{
  alert("Login Failed ! . Check Username and Password.")
}
 
console.log(`${this.state.username}`)

}