You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用React在Sendbird中实现默认聊天群组功能

这个功能完全可以实现,具体实现方向如下:

  • 第一步:预置默认群组
    你可以先在Sendbird管理后台提前创建好需要作为默认入口的2个公开群组,记录下这两个群组的channelUrl。所有新用户完成注册后,你可以选择在后端调用Sendbird服务端接口自动将用户加入这两个群组,也可以在前端初始化Sendbird实例成功后,调用SDK的groupChannel.join()方法主动加入这两个固定channelUrl的群组。
  • 第二步:自定义频道列表展示
    你当前使用的是Sendbird UIKit默认的SendBirdApp全量组件,自带的频道列表默认会展示用户加入的所有群组。如果要将两个默认群组固定在列表顶部、不允许用户删除/退出,你可以拆分默认组件,使用UIKit提供的原子组件自定义布局:
    1. 导入基础组件:将原来导入的SendBirdApp替换为SendBirdProvider、ChannelList、Channel三个基础组件
    2. 布局结构改为外层用SendBirdProvider包裹,左侧放自定义的频道列表,右侧放聊天窗口组件
    3. 自定义频道列表渲染逻辑:优先渲染两个固定的默认群组,再渲染用户加入的其他普通群组,同时可以隐藏默认群组的退出/删除按钮,拦截用户的退出操作。

修改后的代码参考如下:

import React, { useEffect, useState, useRef } from 'react';
import { useHistory } from 'react-router-dom';
import { useSelector } from 'react-redux';

import 'sendbird-uikit/dist/index.css';
// 替换默认导入的App为原子组件
import { SendBirdProvider, ChannelList, Channel } from 'sendbird-uikit';

import { getModuleState as getAuthModuleState } from 'services/auth';
import colorSet from './styled/chatPalette';
import { ChatContainer } from './styled/chatPage';

// 提前配置后台创建的两个默认群组的channelUrl
const DEFAULT_GROUP_URLS = ['你的第一个默认群channelUrl', '你的第二个默认群channelUrl'];

function ChatPage(props) {
  const { theme } = props;
  const history = useHistory();
  const authState = useSelector(getAuthModuleState);
  const userId = authState.username;
  const nickname = authState.username;
  const appId = authState.sendbirdData.appId;
  const accessToken = authState.sendbirdData.accessToken;
  const [currentChannelUrl, setCurrentChannelUrl] = useState(DEFAULT_GROUP_URLS[0]);

  useEffect(() => {
    if (!userId || !nickname) {
      console.error('Error, empty userId or nickname');
    }
  }, [userId, nickname, history]);

  return (
    <ChatContainer>
      <SendBirdProvider
        appId={appId}
        userId={userId}
        nickname={nickname}
        accessToken={accessToken}
        colorSet={colorSet}
      >
        <div style={{ display: 'flex', height: '100%' }}>
          {/* 左侧自定义频道列表 */}
          <ChannelList
            onChannelSelect={(channel) => setCurrentChannelUrl(channel.url)}
            // 自定义频道项渲染,可自行调整默认群组的展示样式和操作限制
            renderChannelPreview={(props) => {
              const { channel } = props;
              return <div onClick={() => setCurrentChannelUrl(channel.url)}>
                {channel.name}
              </div>
            }}
          />
          {/* 右侧聊天窗口 */}
          {currentChannelUrl && (
            <Channel
              channelUrl={currentChannelUrl}
            />
          )}
        </div>
      </SendBirdProvider>
    </ChatContainer>
  );
}

export default ChatPage;

内容的提问来源于stack exchange,提问作者cris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 11:39:02