Kri*_*gji 5 javascript mobile android-softkeyboard reactjs
我有一个简单的聊天视图,还有一个按钮,单击该按钮会将输入字段的值发送到 api(发送消息)
通过移动虚拟键盘插入文本并单击“发送”按钮后,键盘将关闭。
我想阻止这种关闭,以便用户可以发送更多消息,并且只有当他们单击外部键盘时,它才会最终关闭
我的反应代码是这样的:
组件.tsx
<span className="input-group-btn">
<button
ref={submitMessageBtn}
className="btn"
onClick={React.useCallback((event) => {
event.nativeEvent.preventDefault();
sendMessage();
}, [])}
>
{i18n.sendMsgBtn}
</button>
</span>
// somewhere down the function sendMessage
function sendMessage() {
const messageContent = chatMessageInput.current!.value;
chatMessageInput.current!.value = '';
submitMessageBtn.current!.disabled = true;
p.sendMessage(user.id, messageContent).catch((err) => {
// not interesting for question
});
}
Run Code Online (Sandbox Code Playgroud)
我尝试在按钮事件处理程序中preventDefault()但不起作用。我也尝试了event.nativeEvent.stopPropagation(); event.stopPropagation()仍然没有成功。我不明白为什么键盘会关闭(可能是由于失去焦点,但我想保持打开状态)当我单击此按钮时,如何阻止移动(android)虚拟键盘关闭?
这个问题在谷歌上排名很高,这是我如何做到这一点的(使用合成API)
您首先需要获取对文本区域(或输入)的引用,然后当您触发单击事件时,调用此引用值并关注它:
<template>
<textarea
ref="input"
placeholder="Message..."
/>
<button @click="sendMessage">Send</button>
</template>
<script lang="ts" setup>
import { reactive, ref } from "vue";
// if you are using JS, write only const input = ref(null);
const input = ref<null | { focus: () => null }>(null);
async function sendMessage() {
// keep focus back on the input
input.value?.focus();
// input.value.focus(); in JS
// then send the message
// ...
}
</script>
Run Code Online (Sandbox Code Playgroud)
不过,这仅在 Android 上进行了测试