簡體   English   中英

在反應js中單擊按鈕時從class組件導航到功能組件

[英]Navigate from class component to functional component on button click in react js

我有一個 react js class 組件,想導航到一個功能組件並傳遞一些數據。 我在導航時遇到問題。 結構是這樣的,

Class 組件:

export default class Dept extends Component {
     constructor(props) {};
     render() {
    return (
      <>
      <div className="container">
        <Button
                onClick={()=> {
                    //navigate from here to functional component and pass data
              }}
      </div>
     </>
    );
}

功能組件:

export default function Office(props) {
//code
}

我可以使用“useNavigate”從功能組件導航到 class 組件,但不能從 class 導航到功能組件,因為 useNavigate 是一個鈎子。 我嘗試過其他方法,例如編寫另一個功能組件 GoToOffice,它具有導航到 Office 組件的代碼。 但是在 Dept 組件中使用它時單擊按鈕不會導航到 Office。這是我編寫的代碼:

function GoToOffice(props) {
  let navigate = useNavigate();
  navigate("./office", { replace: true });
};

//inside Dept component on button click
<Button onClick={() => {<GoToTemplateList/>}} Test button </Button>

誰能告訴我有什么問題? 如果有人建議在這種情況下導航的方法,那將很有幫助。

這里我嘗試編寫一個包裝器組件,只想導出相應的鈎子(useNavigate,useLocation)。 然后你可以包裝你的 class 組件以使用這些鈎子。

https://stackoverflow.com/a/69962641/17018079

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM