2017-06-19 53 views
0

注意:這與我的問題無關,但我已閱讀this link是否有可能將上下文傳遞給React中的啞元子組件?

說我有我的應用程序組件:

import React, { Component, PropTypes } from 'react'; 

class App extends Component { 
    // stuff & code 
    <Header /> 
    // code & stuff 
} 

App.childContextTypes { 
    router: Proptypes.object.isRequired; 
} 

然後,我有我定義爲一個常數其頁眉部分:

import React, { PropTypes } from 'react'; 

getPath() { 
    const router = { this.context }; 
    return router.location.pathname; 
} 

const Header = (props) => { 
    // header stuff 
    <div>{getPath()}</div> 
} 

Header.contextTypes { 
    router: Proptypes.object.isRequired; 
} 

所有上面是假的代碼,但它的我簡而言之就是。到目前爲止,當我嘗試訪問標題中的路由器對象時,router對象是undefined。是否有可能通過道具以這種方式傳遞給const的組件並且沒有明確定義爲React類?

在我的反應項目中,我使用了react-router。

回答

0

您可以將上下文傳遞給無狀態組件。 React docs

您將在第二個參數中獲取上下文。

const Header = (props, context) => 
{ 
     console.log(context); 
     return (<div></div>); 
} 
Header.contextTypes = { 
    router: Proptypes.object.isRequired; 
} 
相關問題