2017-06-19 55 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>变量。当这个变量在状态中被改变时,它将触发重新渲染到两者,确保它们是最新的。