Botframework V4.6 React WebChat:如何同时显示麦克风与发送按钮?
实现React Web Chat中发送按钮与麦克风按钮共存(移动端)
这个场景我之前帮不少开发者处理过——Bot Framework Web Chat默认在启用语音转文本时,会在移动端将发送按钮替换为麦克风按钮,但确实可以通过自定义组件的方式让两个按钮同时显示,这属于官方支持的扩展方案,不是野路子的workaround,完全合规。
下面是具体实现步骤:
核心思路
Web Chat提供了高度可定制的API,我们可以通过覆盖renderSendBox属性,自定义发送框的布局,把麦克风按钮和发送按钮都整合进去,同时保留原有语音和发送的功能逻辑。
具体实现代码
首先,你需要在Web Chat的渲染代码中传入自定义的SendBox组件:
import React from 'react'; import ReactWebChat from 'botframework-webchat'; const CustomSendBox = ({ sendBoxText, sendMessage, setSendBoxText, startSpeechRecognition, stopSpeechRecognition, isSpeaking }) => { return ( <div style={{ display: 'flex', gap: '8px', padding: '8px', alignItems: 'center' }}> {/* 输入框 */} <input type="text" value={sendBoxText} onChange={(e) => setSendBoxText(e.target.value)} placeholder="输入消息..." style={{ flex: 1, padding: '8px', borderRadius: '4px', border: '1px solid #ccc', fontSize: '14px' }} /> {/* 麦克风按钮 */} <button onClick={() => isSpeaking ? stopSpeechRecognition() : startSpeechRecognition()} style={{ width: '40px', height: '40px', borderRadius: '50%', border: 'none', backgroundColor: isSpeaking ? '#d93025' : '#0078d4', color: 'white', display: 'flex', alignItems: 'center', justifyContent: 'center' }} > {isSpeaking ? '🔴' : '🎤'} </button> {/* 发送按钮 */} <button onClick={() => { sendMessage(sendBoxText); setSendBoxText(''); }} disabled={!sendBoxText.trim()} style={{ padding: '8px 16px', borderRadius: '4px', border: 'none', backgroundColor: '#0078d4', color: 'white', fontSize: '14px', opacity: !sendBoxText.trim() ? 0.5 : 1, cursor: !sendBoxText.trim() ? 'not-allowed' : 'pointer' }} > 发送 </button> </div> ); }; // 在你的组件中渲染Web Chat const YourChatComponent = () => { return ( <ReactWebChat directLine={/* 这里传入你的DirectLine连接对象 */} renderSendBox={(props) => <CustomSendBox {...props} />} // 启用语音转文本的配置 speechOptions={{ speechRecognitionEndpoint: /* 这里传入你的语音转文本服务端点 */ }} /> ); }; export default YourChatComponent;
关键细节说明
- 自定义SendBox时,要接收Web Chat传入的核心props:
sendBoxText(输入框文本)、sendMessage(发送消息方法)、setSendBoxText(更新输入框文本的方法)、startSpeechRecognition/stopSpeechRecognition(语音启停方法)、isSpeaking(是否正在录音的状态),这些都是Web Chat内置的能力,直接复用即可。 - 样式可以根据你的移动端需求调整,比如按钮大小、间距、颜色等,确保在小屏设备上显示紧凑且易用。
- 语音相关的配置(比如
speechOptions)还是按照官方文档正常配置,自定义组件只是修改了UI布局,不会影响语音功能的核心逻辑。
关于官方支持性
Bot Framework Web Chat的设计理念就是支持深度定制,renderSendBox这类渲染回调是官方明确提供的扩展点,所以这种实现方式是完全受支持的,不属于临时的workaround,可以放心在生产环境使用。
内容的提问来源于stack exchange,提问作者Mumin Asaad
相关产品推荐
相关产品推荐

