为什么 select() 在带有 ReactJS 的 Safari 上不起作用? [英] Why does select() not work on Safari with ReactJS?
问题描述
每当我单击/点击/聚焦该字段时,我都希望获得一个 TextField 以选择当前在该字段中的整个文本.以下代码适用于 Chrome (71.0.3578.98),但不适用于 Safari (12.0.2).任何想法为什么?
I'd like to get a TextField to select the whole text currently in the field whenever I click/tap/focus on the field. The following code works in Chrome (71.0.3578.98), but not in Safari (12.0.2). Any ideas why?
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
function App() {
return (
<>
<h1>Test Focus React</h1>
<input
type="text"
defaultValue="test"
onFocus={event => {
event.target.select();
}}
/>
</>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
然而这个没有任何 React 的静态 HTML 文件在 Safari 上运行良好.
And yet this static HTML file without any React works fine on Safari.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Test Focus JS</title>
</head>
<body>
<h1>Test Focus JS</h1>
<input type="text" value="test" onClick="this.select();" />
</body>
</html>
谁能帮我看看如何让选择在带有 React 的 Safari 上工作?
Can anyone help me see how to get the selection to work on Safari with React?
推荐答案
当诸如与 DOM 交互之类的事情失败时,通常与事件如何在不同上下文(react 与 onclick)中同步/异步触发有关,甚至与浏览器(Safari 有时会进行奇怪的优化).
When things like interacting with the DOM fail, it usually is related to how events fire synchronously / asynchronously in different contexts (react vs onclick), and browsers even (with Safari having weird optimisations sometimes).
我猜它会通过使其异步来工作,例如:
I'm guessing it'll just work by making it async, like:
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
function App() {
return (
<>
<h1>Test Focus React</h1>
<input
type="text"
defaultValue="test"
onFocus={event => {
// event properties must be copied to use async
const target = event.target;
setTimeout(() => target.select(), 0);
}}
/>
</>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
这篇关于为什么 select() 在带有 ReactJS 的 Safari 上不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!