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)