React Refs
React Refs
简介
在React中,Refs是React提供的一个API,用于访问组件DOM节点或React组件实例。Refs提供了一种简单而优雅的方式访问组件内部的DOM节点或组件实例,通常用于以下场景:
- 处理焦点、文本选择、或媒体控制等需要直接与DOM交互的情况;
- 触发强制动画或添加额外的功能,如设置组件动画的进入或离开时长;
- 集成第三方DOM库。
注意: 在大多情况下,建议使用props 和 state等React机制来更新和操作组件视图;Refs应仅在必要时使用。
使用Refs情况
创建Refs
Refs是在构造函数中通过createRef()函数创建的:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
render() {
return <div ref={this.myRef} />;
}
}
访问Refs
Refs引用通过current
属性来访问,该属性指向传递给ref属性的节点。
const node = this.myRef.current;
处理React组件
当Ref分配给React组件的时候,Ref对象将接收组件渲染的实例(组件类中的this)作为它的current属性值。
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
// 创建一个 ref 来存储 input 的 DOM 元素
this.textInput = React.createRef();
this.focusTextInput = this.focusTextInput.bind(this);
}
focusTextInput() {
// 直接使用原生 API 使 text 输入框获得焦点
// 注意:通过 "current" 取得 DOM 节点
this.textInput.current.focus();
}
render() {
// 告诉 React 我们想要将 <input> ref 关联到
// 构造器里创建的 `textInput` 上
return (
<div>
<input type="text" ref={this.textInput} />
<input
type="button"
value="Focus the text input"
onClick={this.focusTextInput}
/>
</div>
);
}
}
Refs和函数组件
在函数组件中,Refs通常是使用React Hooks中的useRef Hook来创建:
function CustomTextInput(props) {
// 这里必须用 React.useRef 来创建 refs
const inputRef = React.useRef(null);
function handleClick() {
inputRef.current.focus();
}
return (
<div>
<input type="text" ref={inputRef} />
<input type="button" value="Focus the text input" onClick={handleClick} />
</div>
);
}
总结
Refs是React提供的一个访问组件DOM节点或React组件实例的API。Refs应该仅在必要时使用,并且应当慎用。在大多数情况下,建议使用props和state来更新组件视图,以获得最佳性能和可维护性。在使用Refs时需要注意Refs的使用场景和用法,并遵守其最佳实践。