Typescript React中如何通过按钮点击触发TextInput的contextmenu事件并选中菜单项
解决方案
你当前的问题根源是:contextmenu事件监听绑定在TextInput渲染出来的真实输入框DOM节点上,你现在把事件派发给了父级div#chatti,事件没有触达实际的监听节点,所以没有触发表情菜单效果。
步骤1:给TextInput绑定ref获取真实DOM实例
在函数组件内用useRef创建引用,绑定到TextInput组件上:
import { useRef } from 'react'; // 函数组件内部声明ref const textInputRef = useRef(null);
修改原有TextInput的代码,添加ref属性:
<div id="chatti"> <TextInput ref={textInputRef} value={message} onChangeText={(text) => onChangeMessage(text)} // 其余原有属性、样式保持不变 style={{ // 原有样式 }} /> </div>
步骤2:修改事件派发逻辑,把事件发送给真实输入框节点
调整showCtxMenu函数的实现:
const showCtxMenu = () => { const inputDom = textInputRef.current; // 容错处理:如果还没拿到DOM实例直接返回 if (!inputDom) return; // 部分封装的TextInput需要取下层的真实输入框,可根据打印结果调整,比如: // const inputDom = textInputRef.current.input || textInputRef.current.querySelector('input') || textInputRef.current; const rect = inputDom.getBoundingClientRect(); const ev2 = new MouseEvent("contextmenu", { bubbles: true, cancelable: false, view: window, button: 2, buttons: 0, clientX: rect.x, clientY: rect.y }); inputDom.dispatchEvent(ev2); }
注意:上述方案仅适用于React Web环境,如果是React Native环境,web端的DOM事件API不生效,需要单独适配Native端的表情菜单调用逻辑
内容的提问来源于stack exchange,提问作者smartblonde
相关产品推荐
相关产品推荐

