简体   繁体   English

onClick 按钮返回上一页/组件 React

[英]onClick button to go back to previous page/component React

So I have this div that switch from one component to another by changing the state after clicking on a button.所以我有这个div ,它通过在单击按钮后更改state来从一个组件切换到另一个组件。

{ !showForm ? (
     <div className={styles.showTicketContainer}>
          <div className={styles.showTicketBox}>
               //some code for UI
          </div>
          <div className={styles.whitelistBox}>
                <Button className={styles.whiteListToggleButton} shape="round" onClick={() => setShowForm(() => true)}>Whitelist</Button>
          </div>
      </div>
) : (
   <InputEmail />        // render another component within this div after clicking the whitelist button
)}

So to visualize this is from this to this .因此,要形象化这是从thisthis And I would like to add one button on the email page so that I can go back to the first page .我想在电子邮件页面上添加一个button ,以便我可以返回第一页
Do I still use the same way which is:我是否仍然使用相同的方式:

{ !showForm ? (
      //some UI code
) : ( 
   <someComponent/>
)}

or is there any better way to do this.或者有没有更好的方法来做到这一点。

you can use this:你可以使用这个:

 const history = useHistory();
  history.goBack();

If you're creating pages, I definitely suggest using React Router or a similar library to handle this.如果您正在创建页面,我绝对建议您使用React Router或类似的库来处理此问题。 With React Router, you can easily "back" out to the previous page, and even the "back" button in the user's browser will work, instead of having to click a button.使用 React Router,您可以轻松地“返回”到上一页,甚至用户浏览器中的“返回”按钮也可以使用,而不必单击按钮。

This code will work.此代码将起作用。 Add them wherever required..在需要的地方添加它们..

import { useHistory } from "react-router-dom";

function demo () {
    let history = useHistory();
    const goToPreviousPath = () => {
        history.goBack()
    }
    return (
      <div>
        <Button
          onClick={goToPreviousPath}
        >
          Back
        </Button>
      </div>
    ):
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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