React Router Dom v4 handle browser back button

送分小仙女□ 提交于 2020-03-01 07:45:57

问题


How do I disable a browser back button click from user using react-router-dom v4?

I am showing a modal on a page and when the user presses browser back button then the user is taken to the previous screen, instead I want to simply close the modal.

I tried doing this

onBackButtonEvent(event) {
    event.preventDefault();  
    // the user shouldn't be able to move backward or forward  
}
componentDidMount() {
    window.onpopstate = this.onBackButtonEvent;
}

But this doesn't prevent the user from going backward or forward. Is there a way to handle this via react-router-dom?

I have tried multiple solutions but nothing seems to work.


回答1:


You could create a new Route for your modal and keep it outside of your Switch. This way regular navigation will still apply, and you can also render the modal on top of what is rendered in your Switch.

Example

function Home() {
  return <div> Home </div>;
}

function MyRoute() {
  return (
    <div>
      <h1>MyRoute</h1>
      <Link to="/myroute/edit"> Edit </Link>
      <Route
        path="/myroute/edit"
        render={({ history }) => (
          <ModalComponent history={history}>
            Welcome to the MyRoute edit screen
          </ModalComponent>
        )}
      />
    </div>
  );
}

class ModalComponent extends React.Component {
  onClick = e => {
    e.preventDefault();
    this.props.history.goBack();
  };

  render() {
    return (
      <Modal isOpen>
        <h1> {this.props.children} </h1>
        <Link to="/myroute" onClick={this.onClick}>
          Back
        </Link>
      </Modal>
    );
  }
}

function App() {
  return (
    <BrowserRouter>
      <div>
        <Link to="/"> Home </Link>
        <Link to="/myroute"> My Route </Link>
        <Switch>
          <Route exact path="/" component={Home} />
          <Route path="/myroute" component={MyRoute} />
        </Switch>
      </div>
    </BrowserRouter>
  );
}

const rootElement = document.getElementById("root");
Modal.setAppElement(rootElement);
ReactDOM.render(<App />, rootElement);



回答2:


I know this question's a little old but I stumbled on it while looking for the answer myself. There's no clean way to "disable" the back button but to enable the user to only close the modal when clicking the browser back button I found this to work.

Simply pass the history to your modal component in props and call the below on the componentWillUnmount function.

componentWillUnmount() {
    this.props.history.goForward();
}

This will seamlessly force the browser to stay on the same page but close the modal (assuming it's a class component).



来源:https://stackoverflow.com/questions/51381060/react-router-dom-v4-handle-browser-back-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!