react如何使用agora
使用 React 集成 Agora 实时音视频 SDK
在 React 项目中集成 Agora 实时音视频 SDK 需要安装 SDK 并初始化客户端。以下是一个基本实现流程:
安装 Agora SDK 通过 npm 或 yarn 安装 Agora SDK:
npm install agora-rtc-sdk
# 或
yarn add agora-rtc-sdk
初始化 Agora 客户端 在 React 组件中导入并初始化 Agora 客户端:
import React, { useEffect, useRef } from 'react';
import AgoraRTC from 'agora-rtc-sdk';
const VideoCall = () => {
const clientRef = useRef(null);
const localStreamRef = useRef(null);
useEffect(() => {
// 初始化客户端
clientRef.current = AgoraRTC.createClient({ mode: 'rtc', codec: 'h264' });
return () => {
// 清理资源
if (localStreamRef.current) {
localStreamRef.current.close();
}
if (clientRef.current) {
clientRef.current.leave();
}
};
}, []);
// 加入频道函数
const joinChannel = async (appId, channel, token, uid) => {
try {
await clientRef.current.init(appId);
await clientRef.current.join(token, channel, uid);
// 创建本地流
localStreamRef.current = AgoraRTC.createStream({
audio: true,
video: true,
screen: false
});
await localStreamRef.current.init();
localStreamRef.current.play('local-stream');
await clientRef.current.publish(localStreamRef.current);
} catch (error) {
console.error('加入频道失败:', error);
}
};
return (
<div>
<div id="local-stream" style={{ width: '320px', height: '240px' }}></div>
<button onClick={() => joinChannel('YOUR_APP_ID', 'test', null, null)}>
加入频道
</button>
</div>
);
};
export default VideoCall;
处理远程流
添加远程流处理逻辑以显示其他用户的视频:

useEffect(() => {
if (!clientRef.current) return;
const handleStreamAdded = (evt) => {
const remoteStream = evt.stream;
const id = remoteStream.getId();
clientRef.current.subscribe(remoteStream, (err) => {
if (err) {
console.error('订阅流失败:', err);
return;
}
remoteStream.play(`remote-stream-${id}`);
});
};
clientRef.current.on('stream-added', handleStreamAdded);
return () => {
clientRef.current.off('stream-added', handleStreamAdded);
};
}, []);
添加 UI 元素
在组件中添加远程视频容器:
return (
<div>
<div id="local-stream" style={{ width: '320px', height: '240px' }}></div>
<div id="remote-streams">
{/* 远程流将在这里动态添加 */}
</div>
<button onClick={() => joinChannel('YOUR_APP_ID', 'test', null, null)}>
加入频道
</button>
</div>
);
注意事项
确保替换代码中的 YOUR_APP_ID 为实际的 Agora 项目 App ID。可以从 Agora 控制台获取。

考虑使用环境变量存储敏感信息如 App ID 和 Token。
对于生产环境,建议实现 Token 服务器端生成机制,而不是在前端硬编码。
Agora 提供了 React 专用的 UI 组件库 agora-rtc-react,可以简化开发流程:
npm install agora-rtc-react






