将调度创建的元素聚焦在应用程序的不同部分
我正在使用 React 和 Redux 编写一个有点复杂的应用程序,并且遇到一种情况,单击按钮会调度一个操作,该操作会在应用程序的完全不同的部分中创建一个新的 DOM 元素,并且我希望这个新的 DOM 元素能够获得焦点。我想知道最好的方法是什么。
我设法让它像这样工作:
const handleClick = () => {
ReactDOM.flushSync(() => {
dispatch(createNewElement(id));
});
document.getElementById(id).focus();
};
我使用常规 DOM id 来识别要聚焦的元素,并使用(几乎未记录的)flushSync
函数来确保在选择时它实际上存在于 DOM 中它。
我无法使用 refs,因为新元素位于完全不同的组件中。我无法使用 autoFocus
因为这些元素也可以通过不应该自动聚焦的方式创建,而且我不希望我的 HTML 中到处都是过时的自动聚焦。我不想将焦点状态放在 Redux 存储中,因为正确维护这将是一场噩梦。
我还可以将 .focus
包装在 setTimeout(…, 0)
中,而不是 flushSync
。它似乎有效,但我并不完全相信该元素在超时运行时一定会存在(与 flushSync
不同)。
这是对 ReactDOM.flushSync
的合法使用吗?还有其他更简单的方法吗?
I’m writing a somewhat complex app with React and Redux, and I have a situation where clicking a button dispatches an action that creates a new DOM element in a completely different part of the app and I want this new DOM element to be focused. I’m wondering what’s the best way to do it.
I managed to make it work like this:
const handleClick = () => {
ReactDOM.flushSync(() => {
dispatch(createNewElement(id));
});
document.getElementById(id).focus();
};
I'm using regular DOM ids to identify the element to focus and the (almost undocumented) flushSync
function to make sure that it is actually present in the DOM when selecting it.
I cannot use refs because the new element is in a completely different component. I cannot use autoFocus
because those elements can also be created in ways that should not be autofocused and I don’t want my HTML to be littered with obsolete autofocus's. I don’t want to put the focused state in the Redux store because it will be a nightmare to maintain properly.
Instead of flushSync
I could also wrap the .focus
in a setTimeout(…, 0)
. It seems to work but I’m not entirely convinced that the element is guaranteed to be present by the time the timeout runs (unlike with flushSync
).
Is this a legitimate use of ReactDOM.flushSync
? Is there another simpler way to do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论