如何向BotFramework-WebChat的React组件注入文本并自动发送消息
如何通过Props传入消息并自动发送到BotFramework-WebChat
嘿,我懂你想跳过手动输入,直接通过props把消息传给WebChat组件并自动发送的需求——之前用DOM操作的方法没生效太正常了!毕竟WebChat是React组件,直接碰DOM不仅不是最佳实践,还容易因为组件渲染时机问题找不到目标元素,就算找到了,也没法同步React内部的状态,自然发不出消息。
给你推荐官方支持的正确姿势:利用WebChat内置的Redux store和action来发送消息,这才是和组件内部状态联动的正确方式。
类组件实现示例
首先从botframework-webchat导入需要的模块:
import { Chat, createStore, sendMessage } from "botframework-webchat";
然后改造你的组件:
class ChatBox extends Component { constructor(props) { super(props); // 创建WebChat专属的store,用来管理聊天状态 this.store = createStore(); } componentDidMount() { // 组件挂载完成后,如果props里有初始消息,直接发送 if (this.props.initialMessage) { this.store.dispatch(sendMessage(this.props.initialMessage)); } } componentDidUpdate(prevProps) { // 当传入的消息更新时,发送新的消息 if (prevProps.initialMessage !== this.props.initialMessage) { this.store.dispatch(sendMessage(this.props.initialMessage)); } } render() { return ( <React.Fragment> <div> <Chat directLine={{ secret: "你的DirectLine密钥" }} user={{ id: "Test" }} bot={{ id: "Demo" }} resize={"detect"} store={this.store} // 把自定义store传给Chat组件,让我们能dispatch发送消息的action /> </div> </React.Fragment> ); } }
函数组件实现示例(React Hooks)
如果你的项目用了Hooks,也可以这么写:
import { Chat, createStore, sendMessage } from "botframework-webchat"; import { useEffect, useRef } from "react"; const ChatBox = ({ initialMessage }) => { // 用useRef保存store,避免每次渲染都重新创建 const storeRef = useRef(createStore()); useEffect(() => { // 当initialMessage变化时,发送消息 if (initialMessage) { storeRef.current.dispatch(sendMessage(initialMessage)); } }, [initialMessage]); return ( <div> <Chat directLine={{ secret: "你的DirectLine密钥" }} user={{ id: "Test" }} bot={{ id: "Demo" }} resize={"detect"} store={storeRef.current} /> </div> ); };
为什么之前的方法不行?
你之前直接操作DOM的方式有两个核心问题:
- 渲染时机问题:
componentDidMount触发时,WebChat内部的输入框和发送按钮可能还没完成渲染,导致getElementsByClassName找不到目标元素; - 状态不同步:就算你成功修改了输入框的DOM值,也没有触发WebChat内部的React状态更新,点击发送按钮时,组件拿不到你输入的内容,自然发送失败。
用store dispatch action的方式,是直接和WebChat的状态系统交互,完全符合React的设计理念,也不会有这些问题。
内容的提问来源于stack exchange,提问作者Kaveesha Baddage
相关产品推荐
相关产品推荐

