【发布时间】:2022-09-29 20:21:54
【问题描述】:
我试图集中注意力,然后在 useRef 钩子的帮助下单击输入字段。 我想要实现的是在IOS和ANDROID的手机浏览器中打开输入字段的键盘。 不幸的是,它在我的情况下不起作用,我不知道为什么。 请注意,控制台日志显示已单击。 这是我的代码:
import React, { useEffect, useRef } from \"react\";
import ReactDOM from \"react-dom\";
const App = () => {
const inputRef = useRef();
useEffect(() => {
waiting();
inputRef.current.click();
}, []);
const waiting = async () => {
await inputRef.current.focus();
};
return (
<div>
<input
ref={inputRef}
placeholder=\"input area\"
type=\"tel\"
onClick={() => {
console.log(\"clicked\");
}}
/>
</div>
);
};
const rootElement = document.getElementById(\"root\");
ReactDOM.render(<App />, rootElement);
我正在尝试通过重新实现此 javascript 代码n8jadamsIOS show keyboard on input focus 在 React 中。不确定我是否走在正确的轨道上。 此代码将确保键盘将在 IOS 和 ANDROID 上打开
更新:
得到了这个代码,但它仍然不起作用:
import React, { useEffect, useRef } from \"react\";
import ReactDOM from \"react-dom\";
const App = () => {
const inputRef = useRef();
function focusAndOpenKeyboard(el) {
if (el) {
// Align temp input element approx. to be where the input element is
var __tempEl__ = document.createElement(\"input\");
__tempEl__.style.position = \"absolute\";
__tempEl__.style.top = el.offsetTop + 7 + \"px\";
__tempEl__.style.left = el.offsetLeft + \"px\";
__tempEl__.style.height = 0;
__tempEl__.style.opacity = 0;
// Put this temp element as a child of the page <body> and focus on it
document.body.appendChild(__tempEl__);
__tempEl__.focus();
// The keyboard is open. Now do a delayed focus on the target element
setTimeout(function () {
el.focus();
el.click();
// Remove the temp element
document.body.removeChild(__tempEl__);
}, 100);
}
}
useEffect(() => {
const element = inputRef.current.querySelector(\"input, textarea\");
focusAndOpenKeyboard(element);
}, [inputRef]);
return (
<div ref={inputRef}>
<input placeholder=\"input area\" type=\"tel\" />
</div>
);
};
const rootElement = document.getElementById(\"root\");
ReactDOM.render(<App />, rootElement);
-
严重的是,有人可以帮助我吗?
标签: javascript reactjs