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

Jos*_*ano 4 javascript reactjs

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 "no valid react child"
        </button>
    );
}

//this component is being render as a child of BrowserRouter
class Example extends Component{
    render(){
        return(
            <div>
                <Button path="path/..."/>
            </div>
        );
    }
}

export ...

Run Code Online (Sandbox Code Playgroud)

这是我的实际代码,只是删除了重复的行。对于第一个功能组件,我没有任何问题,但是,我需要为每个按钮创建一个新的功能组件。相反,我正在寻找一种方法来编写此函数一次并使用它来创建许多按钮。

当路径通过 props 传递时,第二个函数不执行任何操作,如果我添加console.log(path)handle()则会在正确传递时打印路径值,但history.push(path)不会采用它。

我想补充一点,我拥有的唯一线索是推送方法文档,其中该方法采用的类型是string,但any正在传递。

Dre*_*ese 5

React 组件只接收一个参数,即 props 对象。你假设有两个。

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 "no valid react child"
    </button>
  );
}
Run Code Online (Sandbox Code Playgroud)

应该

function Button({ path, text }) {
  const history = useHistory();
  function handle(){
    history.push(path); // This should work now
  }
  return(
    <button onClick={handle}>
      {text} // This should render now
    </button>
  );
}
Run Code Online (Sandbox Code Playgroud)

请注意,此处传递的 props 是从props对象中解构的。