2016-09-20 63 views
1

我在tweet中看到了這段代碼,我不明白OnScreenResize是如何實現的,以便提供寬度/高度作爲參數。我並不認爲這些組件是熟悉的,特別是我只想看看它是如何實現的。即孩子的函數如何被調用,並傳遞值react - 組件體中的函數

const LeftIcon = ({ onDrawerToggle }) => (
<OnScreenResize debounce={50} bounds={[400,500]}> 
    {({ width, height }) => 
    width > smallTablet.value 
    ? Component(onDrawerToggle) 
    : OtherComponent()} 
</OnScreenResize> 
) 

回答

2

這是OnScreenResize如何實現:

class OnScreenResize extends Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     width: 0, 
     height: 0  
    }; 
    this.updateWidthAndHeight = this.updateWidthAndHeight.bind(this); 
    } 

    componentWillMount() { 
    this.updateWidthAndHeight(); 
    window.addEventListener('resize', this.updateWidthAndHeight); 
    } 

    componentWillUnmount() { 
    window.removeEventListener('resize', this.updateWidthAndHeight); 
    } 

    updateWidthAndHeight() { 
    this.setState({ 
     width: window.innerWidth, 
     height: window.innerHeight 
    }); 
    } 

    render() { 
    const { width, height } = this.state; 
    return this.props.children({ width, height }); 
    } 
} 
+0

我編輯了問題 – leshow

+0

我剛更新了答案 –

+0

真棒,我會接受您的解決方案。我已經創建了一個小測試項目並且它可以工作。謝謝。 – leshow

0

我不熟悉OnScreenResize組成部分,但它看起來像它期待其children是一個函數。這不是大多數組件的工作原理,但它是一個有效的組件。因此,在渲染時,OnScreenResize會計算寬度和高度,並將其傳遞到this.props.children的函數。然後它呈現返回的內容,在這種情況下,它將根據屏幕寬度成爲兩個組件中的一個。

編輯:添加OnScreenResize組件的示例實現。

const OnScreenResize = ({children}) => { 
    let width = 100 // get width from browser 
    let height = 100 // get height from browser 
    // TODO: error check that children is actually a function instead of assuming. 
    return children({width: width, height: height}) 
} 
+0

反應時添加無狀態的功能部件(在這裏你可以定義組件只是一個渲染功能)這句法成爲可能。它只是定義了一個匿名函數值來代替傳統的React組件。 – Brandon

+0

我不希望任何人熟悉那個組件,問題是假設。我只想看看寬度和高度會通過的代碼 – leshow

+0

查看我上面的編輯 –

相關問題