2016-04-08 13 views
1

私は、ウィンドウオブジェクト上のリサイズイベントのイベントリスナーを持つReact Appを持っています。リサイズ変更コンポーネントを変更する

class App extends React.Component { 
    constructor(props){ 
    super(props); 

    this.state = { width: 0 } 
    this.setSize = this.setSize.bind(this); 
    } 

    render() { 
    let content = this.state.width < 600 ? <MobileComponent/> : <DesktopComponent />; 
    return(<div>{content}</div>) 
    } 

    setSize() { 
    this.setState({ 
     width: window.innerWidth 
    }); 
    } 

    componentDidMount() { 
    this.setSize(); 
    window.addEventListener('resize', this.setSize); 
    } 

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

この問題は機能しますが、私の問題は、子コンポーネント内のAppコンポーネント(ウィンドウの幅)の状態にアクセスする方法がわかりませんということです。

だから、誰かが/アクセス(私は小道具を送信することができます知っているが、私の中で、私は2種以上の成分を何を持っている場合は?)

+0

あなたはそれを小道具で送ることができ、それを複数の子コンポーネントに送ることができます。 – Ved

答えて

3
 render() { 
     let content = this.state.width < 600 ? <MobileComponent/> : <DesktopComponent />; 
     return(<div> 
      <div>{content}</div> 
      <childComponent myWidth= {this.state.width}></childComponent > 
      <childComponent2 myWidth= {this.state.width}></childComponent2 > 
     </div> 
    ) 
} 
私の子コンポーネントにthis.state.widthを送信する方法を私に説明することができます
+0

答えに感謝し、childComponentにchildComponentがある場合は、私も小道具を追加する必要がありますか?その良い練習ですか? – Hiero

+0

はい。あなたはできる。 chilcomponentが同じアプローチに従うよりもchildcomponentを持っているなら。 – Ved

関連する問題