React Refs属性
封面图
•
2025-10-11
•
React
0
0
0
0
在 React 中,**Refs(引用)** 是一种用于访问 DOM 节点或 React 组件实例的机制。它们在某些场景下非常有用,例如: - 直接操作 DOM(如聚焦输入框、播放视频等) - 调用组件的方法(如调用子组件的某个方法) - 存储一些不需要触发重新渲染的状态 --- ## 📌 1. 创建 Ref 的方式 ### ✅ 使用 `useRef` 钩子(函数组件中使用) ```jsx import React, { useRef } from 'react'; function MyComponent() { const inputRef = useRef(null); const focusInput = () => { inputRef.current.focus(); }; return ( <div> <input ref={inputRef} type="text" /> <button onClick={focusInput}>Focus Input</button> </div> ); } ``` - `useRef()` 返回一个可变对象 `{ current: ... }` - `.current` 属性可以保存任意值,包括 DOM 元素或组件实例 --- ### ✅ 使用 `createRef`(类组件中使用) ```jsx class MyComponent extends React.Component { constructor(props) { super(props); this.inputRef = React.createRef(); } focusInput = () => { this.inputRef.current.focus(); }; render() { return ( <div> <input ref={this.inputRef} type="text" /> <button onClick={this.focusInput}>Focus Input</button> </div> ); } } ``` --- ## 📌 2. Ref 的常见用途 ### 🔧 1. 操作 DOM ```jsx const inputRef = useRef(); useEffect(() => { inputRef.current.focus(); // 自动聚焦 }, []); ``` ### 🔄 2. 调用子组件的方法 ```jsx function ParentComponent() { const childRef = useRef(); const handleCallChildMethod = () => { childRef.current.someMethod(); }; return ( <div> <ChildComponent ref={childRef} /> <button onClick={handleCallChildMethod}>Call Child Method</button> </div> ); } function ChildComponent({ ref }) { useImperativeHandle(ref, () => ({ someMethod: () => console.log("Called from parent!") })); return <div>Child Component</div>; } ``` > 注意:要使用 `useImperativeHandle` 来暴露子组件的方法给父组件。 --- ## 📌 3. 使用 `useImperativeHandle`(控制暴露给父组件的 API) ```jsx function ChildComponent({ ref }) { const inputRef = useRef(); useImperativeHandle(ref, () => ({ focus: () => inputRef.current.focus(), value: inputRef.current?.value })); return <input ref={inputRef} />; } ``` --- ## 📌 4. 注意事项 | 特性 | 说明 | |------|------| | **不要滥用 Ref** | Ref 不应该用来替代状态管理,除非确实需要直接操作 DOM 或组件实例 | | **不能在函数组件中使用 `this.refs`** | 在函数组件中只能使用 `useRef` | | **避免在渲染中使用 Ref** | 例如不要在 `render` 函数中修改 `ref.current`,这可能导致性能问题或副作用 | --- ## 📌 5. Ref 的生命周期 - 当组件被挂载时,`ref.current` 会被赋值为对应的 DOM 节点或组件实例 - 当组件被卸载时,`ref.current` 会被置为 `null` --- ## 📌 6. 常见错误 - **错误地将 `ref` 作为 prop 传递给子组件(非受控组件)** 如果你希望子组件暴露某些方法,应使用 `useImperativeHandle`,而不是直接传递 `ref` - **尝试在 `useEffect` 中访问未初始化的 `ref`** 确保 `ref` 已经被正确绑定(例如在 `useEffect` 中访问 `ref.current` 时,组件已经渲染完成) --- ## ✅ 总结 | 类型 | 用法 | 适用场景 | |------|------|----------| | `useRef()` | 函数组件中创建 Ref | 操作 DOM、存储变量、调用子组件方法 | | `React.createRef()` | 类组件中创建 Ref | 与类组件兼容 | | `useImperativeHandle()` | 控制暴露给父组件的 API | 仅在需要暴露方法时使用 | --- 如果你有具体的应用场景(比如如何聚焦输入框、如何调用子组件方法等),我可以给你更详细的示例!
上一篇:
React 组件生命周期
下一篇:
Flutter文本及样式
标题录入,一次不能超过6条
返回顶部
留言
留言
评论