簡體   English   中英

如何將歷史道具與其他道具一起使用

[英]How do I use history prop with other props

我正在使用react-router-domreact 我正在嘗試使用history prop獲得其他道具

import React from 'react';

function MyComponent({ history }) {
   function redirect() {
      history.push('/path');
   }

   return (
      <>
         <button onClick={redirect}>Some Button</button>
      </>
   );
}

export default MyComponent;

這會起作用,但如果我放另一個這樣的道具

function MyComponent({myFunction, history}) {}

這行不通

有沒有其他選擇,或者我做錯了什么?

相反,您可以使用react-router-dom中的useHistory()鈎子。 從文檔中閱讀:

useHistory掛鈎使您可以訪問可用於導航的歷史實例。

嘗試如下:

import React from 'react';
import { useHistory } from 'react-router-dom';

function MyComponent({ myFunction }) { // here still you can pass other props
   let history = useHistory(); // meanwhile you have the history object

   function redirect() {
      history.push('/path');
   }

   return <>
      <button onClick={redirect}>Some Button</button>
   </>
}

export default MyComponent;

如果您需要一個完整的示例,請在下面找到我的 GitHub 存儲庫之一: https://github.com/norbitrial/react-router-programmatically-redirect-examples

我建議從那里看一下這個文件 我已經在我的代碼片段中包含了上面的基本工作示例。

我希望這有幫助!

試試這個 - 你可以收到盡可能多的道具。

import React from 'react';
import { useHistory } from 'react-router-dom';

function MyComponent() {
const history = useHistory();
   function redirect() {
      history.push('/path');
   }

   return (
      <>
         <button onClick={redirect}>Some Button</button>
      </>
   );
}

export default MyComponent;

暫無
暫無

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

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