小编Jos*_*ano的帖子

ReactJS Router-如何在带参数的功能组件中使用历史推送?

history.push("path/...")我在函数组件中使用时遇到问题。我的问题是当我尝试在按钮处理程序中使用函数组件的参数时。我有下一个代码: Example.js

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

//This function works fine, but i would prefer something reusable
function Button() {
    const history = useHistory();
    function handle(){
        history.push("/path"); //The path is harcoded
    }
    return(
        <button onClick={handle}>
            Home //This text is harcoded
        </button>
    );
}

//This is what i'm looking for, because i would write it once.
function Button(path, text) {
    const history = useHistory();
    function handle(){
        history.push(path); //This doesn't work
    }
    return(
        <button onClick={handle}>
            {text} //This throws an error …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs

4
推荐指数
1
解决办法
3055
查看次数

标签 统计

javascript ×1

reactjs ×1