每当我单击/点击/聚焦于该字段时,我希望获得一个TextField来选择该字段中当前的整个文本。以下代码适用于Chrome (71.0.3578.98),但不适用于Safari (12.0.2)。你知道为什么吗?
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上工作得很好。
<!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上进行选择?
发布于 2019-01-17 13:32:44
我认为您希望使用React ref来存储对实际input DOM元素的引用,以便可以从onClick方法对其调用select。
请参阅文档,它们有一个很好的示例,您可以稍微修改一下以满足您的需求:https://reactjs.org/docs/refs-and-the-dom.html
我认为这应该是可行的:
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
this.textInput = React.createRef();
this.selectTextInput = this.selectTextInput.bind(this);
}
selectTextInput() {
this.textInput.current.select();
}
render() {
return (
<div>
<input
type="text"
defaultValue="pizza"
ref={this.textInput}
onClick={this.selectTextInput}
/>
</div>
);
}
}
function App() {
return (
<CustomTextInput />
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);https://stackoverflow.com/questions/54229359
复制相似问题