【发布时间】:2020-10-04 04:13:43
【问题描述】:
我是 React 世界的新手,正在学习 Refs。 React 文档说:
Refs 提供了一种访问 DOM 节点或 React 元素的方法 渲染方法。
我认为我们可以用 querySelector 函数做同样的事情。
React 文档提供了一个示例,说明我们如何使用 Refs 来关注输入元素。
这是代码 ->
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
// create a ref to store the textInput DOM element
this.textInput = React.createRef();
this.focusTextInput = this.focusTextInput.bind(this);
}
focusTextInput() {
// Explicitly focus the text input using the raw DOM API
// Note: we're accessing "current" to get the DOM node
this.textInput.current.focus();
}
render() {
// tell React that we want to associate the <input> ref
// with the `textInput` that we created in the constructor
return (
<div>
<input
type="text"
ref={this.textInput} />
<input
type="button"
value="Focus the text input"
onClick={this.focusTextInput}
/>
</div>
);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
用 querySelector 做同样的事情 ->
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
this.textInput = React.createRef();
}
focusTextInput = () => {
const input = document.querySelector("input");
input.focus();
};
render() {
return (
<div>
<input type="text" ref={this.textInput} />
<button type="button" onClick={this.focusTextInput}>
Focus the Text Input
</button>
</div>
);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
【问题讨论】:
-
假设文档中有多个输入。你怎么知道你的 querySelector 返回了正确的?如果您的组件在同一个视图中多次使用怎么办?
-
@rayhatfield 我们可以将 id 添加到输入中
-
重要提示:
.querySelector--> 返回文档中与指定选择器或选择器组匹配的第一个元素。.querySelectorAll()--> 返回一个静态(非实时)NodeList,表示与指定选择器组匹配的文档元素列表。 -
querySelector()在所有 html 元素中搜索以找到目标元素,但使用ref您可以直接访问该元素。此外,您要查找的元素可能会发生变化,例如它的cssClass可能会被删除,您将无法再找到它。 -
过度简化的原因是 React 会随着状态的变化替换 dom 中的现有元素,尽管它们看起来相同并且具有相同的属性,但它们每次都不是完全相同的元素对象。 React 在后台执行此操作,您应该关注的是状态而不是 dom
标签: javascript html reactjs