我如何将历史道具与其他道具一起使用

问题描述 投票:0回答:2

我正在将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}) {}

这不起作用

是否有其他替代方法,或者我做错了什么?

javascript reactjs react-hooks react-router-dom history
2个回答
0
投票

尝试一下-您可以接收任意数量的道具。

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;

0
投票

相反,您可以使用react-router-dom中的useHistory()钩子。阅读文档:

useHistory()挂钩使您可以访问可用于导航的历史记录实例。

尝试以下操作:

useHistory

[如果您需要一个完整的示例,请在下面找到我的GitHub存储库之一: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;

我建议从那里看一下https://github.com/norbitrial/react-router-programmatically-redirect-examples。我已经在代码段中包含了上面的基本工作示例。

我希望这会有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.