如何在父子组件之间使用回调函数

时间:2019-01-23 23:07:28

标签: javascript reactjs react-native

我的问题是我想处理组件之间的活动链接(<a class="active" >)。

介绍:

在选择频道时,同时从直接消息组件中选择一个用户。在这种情况下,两个链接“ <a>”将处于活动状态。

Sidebar

父类:

class SidePanel {

    render(){

        const {currentUser} = this.props;

        return(
            <Menu>
               // Childs :
               <Channels currentUser={currentUser} />{' '}
               <DirectMessages  currentUser={currentUser} />

            </Menu>
        );
    };

}

1 个答案:

答案 0 :(得分:0)

我将在Parent中执行发送消息的过程,并注入直接消息的结果 到DirectMessages组件,如下所示。

在您的Channel组件中

...

class channel extens Component {
  handleChannelSelect = (channelId) => {
    if this.props.handleChannelSelect && this.props.handleChannelSelect(channelId);
  }
}

...

SidePanel(父组件)

   class SidePanel {
     handleChannelSelect = async (channelId) => {
      const messageResult = await serverApi.sendDirectMessage(channelId);
      this.setState({ messageResult });
    }

    return(
      <Menu>
        // Childs :
        <Channels currentUser={currentUser} handleChannelSelect={this.handleChannelSelect}/>{' '}
        <DirectMessages  currentUser={currentUser} messages={this.state.messageResult} />
      </Menu>
    );
  }

为什么

这不是固定的方式,但是我更喜欢在Top屏幕组件中使用后端流程,或使用流量架构来控制客户端与服务器之间的通信。并使组件集中如何显示结果。

Flux

相关问题