2017-04-05 24 views
2

我想知道是否window對象傳遞到反應組件合成與否。React合成的窗口對象?

如果不是我假設我需要下面的代碼來確定視

const w = window, 
    d = document, 
    documentElement = d.documentElement, 
    body = d.getElementsByTagName('body')[0], 
    width = w.innerWidth || documentElement.clientWidth || body.clientWidth, 
    height = w.innerHeight || documentElement.clientHeight || body.clientHeight 

回答

6

window對象的寬度和高度是正常的DOM對象。

問題在於它只有在組件安裝後纔可用。

componentDidMount() { 
    const w = window, 
    d = document, 
    documentElement = d.documentElement, 
    body = d.getElementsByTagName('body')[0], 
    width = w.innerWidth || documentElement.clientWidth || body.clientWidth, 
    height = w.innerHeight || documentElement.clientHeight || body.clientHeight 
} 

https://facebook.github.io/react/docs/react-component.html#componentdidmount

更新:

如果DOM加載之前反應過來,window對象在componentWillMount可用。只要您沒有在文檔的<head>中加載React,我認爲使用componentWillMount就好了。

注意:即將呈現的實際組件不會存在,但window可能存在。

+1

你可能想改變方法名稱,我認爲它開始於小'c' –

+0

@ArchimedesTrajano糟糕。更新。 –

+0

你也注意到它是在它被安裝的時候,但這會抵觸http://stackoverflow.com/questions/19014250/reactjs-rerender-on-browser-resize –

0

在React中訪問窗口對象和其他地方一樣。它存在於任何JavaScript運行之前。作爲測試,在你的地址欄中輸入about:blank,打開控制檯並輸入'window'。它甚至在頁面上沒有其他JavaScript。