【发布时间】:2020-08-05 18:48:15
【问题描述】:
我正在使用 Antd Mobile 组件库编写一个带有客户端渲染的 React 非原生 webapp。
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-redux": "^7.2.0",
"react-redux-router": "0.0.14",
"react-router-dom": "^5.2.0",
"antd": "^4.4.0",
"antd-mobile": "^2.3.3",
我有一个带有 2 个文本区域作为受控组件的小表单。当用户在桌面浏览器(safari、firefox、chrome 等)上编辑文本时,它可以正常工作而不会失去焦点。但是在 webkit 上,这些字段在模型更新 render() 期间失去焦点。我正在使用静态字符串键并已实现 ref 挂钩来重置焦点和光标位置。每次击键后,虚拟键盘消失,光标从文本区域中移除。该模块被编写为“纯”功能组件(而不是类)。
任何想法为什么 webkit 会遇到这个问题?
下面是感兴趣的部分代码:
const useFocus = () => {
const htmlElRef = useRef(null);
const setFocus = () => {
htmlElRef.current && htmlElRef.current.focus();
};
return [htmlElRef, setFocus];
};
const [focusRef, setFocusRef] = useFocus();
[snip]
key="myfieldkey"
name="myfield"
title="MyLabel:"
ref={focusRef}
onChange={(value) => {
let cursorStart =
focusRef.current.textareaRef.selectionStart;
onFieldChange(value /* update model */ );
/* timeout gives reducer time to update model */
setTimeout(() => {
setFocusRef();
focusRef.current.textareaRef.setSelectionRange(
cursorStart,
cursorStart
);
}, 40);
}}
【问题讨论】:
标签: reactjs webkit focus textarea render