如何通过 React 中的 Link 传递函数?

IT技术 reactjs react-router jsx
2021-05-06 08:31:29

我必须通过 Link 将函数传递给另一个组件。

    testFavorite=()=>{
        console.log("work")
    }

    <Link 
       to={{
       pathname: '/popular',
         state:{
            testFavorite: this.testFavorite
         }
       }}>
   Popular</Link>

这就是我调用函数的方式

this.props.location.state.testFavorite();

但我有这个错误

history.js:370 未捕获的 DOMException:无法在“History”上执行“pushState”:function () { console.log("work"); 无法克隆。

我该如何解决?非常感谢

编辑 blazing-resonance-qgi2m

1个回答

当您用数据替换状态时可以完成。

<Link 
       to={{
       pathname: '/popular',
         data:{
            testFavorite: this.testFavorite
         }
       }}>

也替换这里

this.props.location.state.testFavorite();

同时,如果您还想将数据作为props传递,您可以将状态与数据一起使用