如何使用链接组件转到具有onClick属性的另一个页面?

时间:2019-07-10 14:03:14

标签: reactjs

大家好,我在下订单时有以下按钮,但是在收到handleSubmit()的回复后,我想进入/order页面。

<Link
    to="/order"
    onClick={this.handleSubmit}
    className="FormField__Button_Order"
    style={{
      textDecoration: "none",
      color: "#433969"
    }}
    >
    Order Now
</Link>

2 个答案:

答案 0 :(得分:1)

错误在onClick中使用<Link />,解决方案:-

import React from 'react';
import { withRouter } from 'react-router-dom';

class App extends React.Component{
    handleSubmit = (event) => {
        this.props.history.push('/order');
    }
    render(){
        return(
        <button onClick={(event) => this.handleSubmit(event)}>Order Now</button>        
    }
}

export default withRouter(App); 

to use history as a props in this component, wrap componentName with withRouter

答案 1 :(得分:0)

您可以使用按钮来调用句柄提交,然后使用重定向组件来重定向到您的页面:Redirecting in React

import React from 'react'
import { Redirect } from 'react-router-dom'
class MyComponent extends React.Component {  
    state = {
        redirect: false
    }
    setRedirect = () => {
      this.setState({
        redirect: true
      })
    }
  renderRedirect = () => {
    if (this.state.redirect) {
      return <Redirect to='/target' push />
    }
  }
  render () {
    return (
       <div>
        {this.renderRedirect()}
        <button type='button' onClick={this.setRedirect}>Redirect</button>
       </div>
    )
  }
}