2017-06-19 56 views
0

你好我是新的反應,我試圖加載<API-Result/>內容取決於在<Navigation>點擊什麼。我不確定如何在<Navigation>中觸發與<Api-Result/>通信並顯示正確內容的活動。如何通知<Api-Result/>點擊了哪些內容?React檢測組件外部點擊什麼

之間不存在關係:兒童

  • 孩子家長

我在我的<App>結構

<Header> 
<Navigation /> //<----- here is menu 
    ... 
</Header> 

<Content Grid> 
    <Api-Result /> //<----- here is the content 
</Content Grid> 
+0

[檢測點擊外部React組件]可能重複(https://stackoverflow.com/questions/32553158/detect-click-outside-react-component) – lux

回答

1

一般的解決方法是讓在樹的某處,將數據和動作委託給它的c承運。由於React將自己塑造爲「樹」,這意味着在某些時候這些組件將共享一個父項。我們只是說它叫<AppContainer>

<AppContainer> <-- this will delegate the data to the components below it 
    <Header> 
    <Navigation /> 
    </Header> 
    <Content Grid> 
    <ApiResult /> 
    </Content Grid> 
</AppContainer> 

然後你扯起功能到<AppContainer>,其代表的數據在它下面的組件。假設點擊菜單顯示「已保存」項目。你可能會喜歡這款機型的行爲:

class AppContainer extends Component { 
    state = { showSaved: true }; 

    onMenuClick =() => { 
    this.setState({ showSaved: true }); // example 
    }; 

    render() { 
    return (
     <div> 
     <Header> 
     <Navigation 
      showSaved={this.state.showSaved} 
      onMenuClick={this.onMenuClick} 
     /> 
     </Header> 
     <ContentGrid> 
     <ApiResult menuClicked={this.state.showSaved} /> 
     </ContentGrid> 
     </div> 
    ); 
    } 
} 

這將允許您訪問兩個<ApiResult><Navigation>變量。當這個變量在狀態中被改變時,它將觸發重新渲染到兩者,確保它們是最新的。