2016-05-30 403 views
25

據我所知<Route path="/" component={App} />將給出App路由相關的道具,如locationparams。如果我的App組件具有許多嵌套子組件,我怎麼子組件能夠獲得這些道具,而不:使用window對象 react-router在子組件中獲取this.props.location

  • 創建路由嵌套子組件

    • 從應用
    • 通過道具

    我以爲this.context.router會有一些與路線有關的信息,但this.context.router似乎只有一些功能來操縱路線。

  • +0

    在應用程序組件的上下文子組件,直接嵌套子組件可以在this.props.children –

    回答

    43

    (更新)V4

    你可以以注入matchhistorylocation在組件道具使用withRouter HOC。

    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以注入routerparamslocationroutes在組件中的道具。

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

    原來的答覆

    如果你不想使用道具,你可以使用上下文關係中React Router documentation

    首先說明,你必須設置你的childContextTypesgetChildContext

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

    然後,您將能夠訪問您的位置對象使用這樣

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

    感謝指針找到。我沒有閱讀那部分文檔。我以爲只有'''context.router''' – xiaofan2406

    +0

    你應該提[如果你想你的應用程序是穩定的,不使用環境。這是一個實驗性的API,它很可能在陣營的未來版本中破解](https://facebook.github.io/react/docs/context.html#why-not-to-use-context)。 –