React Refs 知识点详解
专门为编程小白准备的通俗易懂的React Refs指南
什么是Refs?
Refs 是 React 提供的一种特殊功能,它允许你直接访问 DOM 节点或 React 组件实例。
通俗地说:Refs 就像给你的React元素贴上一个标签,然后你可以通过这个标签直接找到它,而不是通过React的常规数据流。
📌 关键点: Refs 是对 DOM 节点或组件实例的直接引用
使用场景:
- 管理焦点、文本选择或媒体播放
- 触发强制动画
- 集成第三方 DOM 库
- 访问子组件的DOM元素
创建Refs的三种方式
1. 字符串Refs(已过时)
// 旧方式,不推荐使用
<input ref=”myInput” />
2. 回调Refs
// 通过回调函数设置ref
<input ref={(element) => this.inputElement = element} />
3. createRef() API(推荐)
// 现代React推荐方式
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
render() {
return <div ref={this.myRef} />;
}
}
如何使用Refs?
访问 DOM 元素
class AutoFocusInput extends React.Component {
constructor(props) {
super(props);
this.inputRef = React.createRef();
}
componentDidMount() {
// 组件挂载后自动聚焦输入框
this.inputRef.current.focus();
}
render() {
return (
<input ref={this.inputRef} />
);
}
}
访问类组件实例
class CustomTextInput extends React.Component {
// …
}
class ParentComponent extends React.Component {
constructor(props) {
super(props);
this.textInput = React.createRef();
}
handleClick = () => {
this.textInput.current.focus(); // 调用子组件的方法
};
render() {
return (
<>
<CustomTextInput ref={this.textInput} />
<button onClick={this.handleClick}>聚焦输入框</button>
</>
);
}
}
Refs的注意事项
⚠️ 重要提示: 不要滥用Refs!
- Refs 应该作为最后的手段,优先考虑使用React的状态和属性
- 不能在函数组件上使用 ref 属性(除非使用 forwardRef)
- 避免在渲染期间访问 refs.current,因为 refs 在更新前可能为 null
- 函数组件使用 useRef() Hook 来创建 refs
- 改变 DOM 时要注意,可能会与 React 的渲染机制冲突
函数组件中使用Refs
function TextInput() {
const inputRef = useRef(null);
useEffect(() => {
inputRef.current.focus();
}, []);
return <input ref={inputRef} />;
}
Refs与状态(state)的区别
特性 | Refs | State |
---|---|---|
触发重新渲染 | ❌ 不会 | ✅ 会 |
访问方式 | 通过 .current 属性 | 直接访问 |
可变性 | 可以直接修改 | 必须通过 setState() |
使用场景 | 访问DOM/组件实例 | 存储渲染数据 |
更新时机 | 同步更新 | 异步更新 |
💡 经验法则: 如果某个值不会影响渲染逻辑,应该使用ref而不是state