如何在有状态组件中的 react router 5.1.2 中使用 history.push('path') ? [英] How can I use history.push('path') in react router 5.1.2 in stateful component?
本文介绍了如何在有状态组件中的 react router 5.1.2 中使用 history.push('path') ?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在有状态组件(类组件)中的 react router 5.1.2 中使用 history.push('path') ?
我找到了这个,但它是无状态组件的解决方案.
import { useHistory } from react-router-dom";功能应用(){让历史 = useHistory();}
解决方案
这是你可以使用 this.props.history.push('/...')
导航到其他组件的方法有状态/基于类的组件.
const BasicExample = () =>(<路由器><div><ul><li><链接到="/">主页</链接><li><Link to="/about">关于</Link><小时/><路由精确路径="/" component={Home}/><Route path="/about" component={About}/>
</路由器>);const 关于 = () =>(<div><h2>关于</h2>
);class Home 扩展 React.Component {handleClick = e =>{this.props.history.push("/about");};使成为() {返回 (<div><h2>家</h2><button onClick={this.handleClick}>点击浏览页面</button>
);}}
How can I use history.push('path') in react router 5.1.2 in stateful component (class component)?
I found this, but it is a solution for a stateless component.
import { useHistory } from "react-router-dom";
function App() {
let history = useHistory();
}
解决方案
This is how you can navigate to other component using this.props.history.push('/...')
in stateful/class based component.
const BasicExample = () => (
<Router>
<div>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
</ul>
<hr />
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
</div>
</Router>
);
const About = () => (
<div>
<h2>About</h2>
</div>
);
class Home extends React.Component {
handleClick = e => {
this.props.history.push("/about");
};
render() {
return (
<div>
<h2>Home</h2>
<button onClick={this.handleClick}>Click to navigate about page</button>
</div>
);
}
}
这篇关于如何在有状态组件中的 react router 5.1.2 中使用 history.push('path') ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!