简体   繁体   中英

React => Make action on back button on Android Google Chrome (Not React Native)

I have a case where there is the application written in React (not React Native).

The application runs on the web. So for example I use Google Chrome on my mobile (android).

I'm on some URL in my app. Is it possible to add some action when the user clicks the 'back icon'? To move to the previous page for example?

I know that we can easily achieve it on React Native, but in just React?

I mean this back icon:

在此处输入图像描述

Is it possible?

Thanks

You can use React Router there is a hook called useHistory you can use it go back in React

import React from "react";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link,
  useHistory
} from "react-router-dom";

const Foo = () => {
  const history = useHistory();

  return (
    <div>
      <button onClick={history.goBack}>Back</button>
      <p>foo</p>
    </div>
  );
};

const Bar = () => {
  const history = useHistory();

  return (
    <div>
      <button onClick={history.goBack}>Back</button>
      <p>bar</p>
    </div>
  );
};

export default function App() {
  return (
    <Router>
      <div>
        <ul>
          <li>
            <Link to="/foo">foo</Link>
          </li>
          <li>
            <Link to="/bar">bar</Link>
          </li>
        </ul>

        <Switch>
          <Route path="/foo" children={<Foo />} />
          <Route path="/bar" children={<Bar />} />
        </Switch>
      </div>
    </Router>
  );
}

for more details on this you follow this docs page

It sounds like a new problem, but maybe somebody had a similar case?

Thanks in advance

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM