javascript - react-router中嵌套的子组件拿location对象的问题
仅有的幸福
仅有的幸福 2017-06-26 10:50:02
[JavaScript讨论组]

比如说一个页面有个modal组件,modal组件里面的内容写在子组件里面(ModalDetail),在这个组件里面拿不到this.props.location,求解答,除了从父组件传进去和通过window对象拿,还有什么方法

仅有的幸福
仅有的幸福

全部回复(2)
某草草

react-router v4之前的版本,有一个叫做withRouter的高阶组件。你在定义自己的modal组件时包一层即可。

v4版本暂时没有用过,有没有改动不清楚

import React from 'react'
import PropTypes from 'prop-types'
import { withRouter } from 'react-router'

// A simple component that shows the pathname of the current location
class ShowTheLocation 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 (
      <p>You are now at {location.pathname}</p>
    )
  }
}

// Create a new component that is "connected" (to borrow redux
// terminology) to the router.
export default withRouter(ShowTheLocation)

包一层withRouter之后,就可以访问到你想要的属性了,你还可以进一步学习,看看里面都有些什么。

PHP中文网

还可以使用withRouter,通过this.props.location获取

import React, { Component } from 'react';
import { withRouter } from 'react-router'


class  MyComponent extends Component {

   .....
}

export default withRouter(MyComponent)
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号