栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

react

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

react

(更新)V5.1和Hooks(需要React > = 16.8)

您可以使用

useHistory
useLocation
useRouteMatch
在你的组件来获得
match
history
location

const Child = () => {  const location = useLocation();  const history = useHistory();  const match = useRouteMatch("write-the-url-you-want-to-match-here");  return (    <div>{location.pathname}</div>  )}export default Child

(更新)V4和V5

您可以使用

withRouter
,以HOC注入
match
history
location
在组件的道具。

class Child extends React.Component {  static propTypes = {    match: PropTypes.object.isRequired,    location: PropTypes.object.isRequired,    history: PropTypes.object.isRequired  }  render() {    const { match, location, history } = this.props    return (      <div>{location.pathname}</div>    )  }}export default withRouter(Child)

(更新)V3

您可以使用

withRouter
HOC以注入
router
params
location
routes
在组件中的道具。

class Child extends React.Component {  render() {    const { router, params, location, routes } = this.props    return (      <div>{location.pathname}</div>    )  }}export default withRouter(Child)

原始答案

如果您不想使用道具,可以使用React Router文档中所述的上下文

首先,你必须设置你的

childContextTypes
getChildContext

class App extends React.Component{  getChildContext() {    return {      location: this.props.location    }  }  render() {    return <Child/>;  }}App.childContextTypes = {    location: React.PropTypes.object}

然后,您将可以使用这样的上下文访问子组件中的location对象

class Child extends React.Component{   render() {     return (       <div>{this.context.location.pathname}</div>     )   }}Child.contextTypes = {    location: React.PropTypes.object }


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/382983.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号