react-router go back a page how do you configure history?

前端 未结 21 1291
说谎
说谎 2020-11-30 18:30

Can anyone please tell me how I can go back to the previous page rather than a specific route?

When using this code:

var BackButton = React.createCla         


        
21条回答
  •  盖世英雄少女心
    2020-11-30 18:54

    What worked for me was to import withRouter at the top of my file;

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

    Then use it to wrap the exported function at the bottom of my file;

    export default withRouter(WebSitePageTitleComponent)
    

    Which then allowed me to access the Router's history prop. Full sample code below!

    import React, { Component } from 'react'
    import { withRouter } from 'react-router-dom'
    
    import PropTypes from 'prop-types'
    
    class TestComponent extends Component {
      constructor(props) {
        super(props)
        this.handleClick = this.handleClick.bind(this)
      }
    
      handleClick() {
        event.preventDefault()
        this.props.history.goBack()
      }
    
      render() {
        return (
          
        )
      }
    }
    
    const { string, object } = PropTypes
    
    TestComponent.propTypes = {
      title: string.isRequired,
      history: object
    }
    
    export default withRouter(TestComponent)
    

提交回复
热议问题