1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| 在 React Native(以及 React)中,refs(引用)用于直接访问 DOM 节点或组件实例。 关于 refs,你可以了解以下几个关键点
1. refs 的作用 -在需要直接操作 DOM 或组件实例的情况下使用 refs, 例如获取组件的值、调用方法、控制焦点、执行动画等。
-适用于无法通过 state 和 props 实现的需求
2. 创建 refs 的方式 React 提供了两种主要的方式来创建 refs
2.1 useRef(函数式组件)
import { useRef, useEffect } from 'react'; import { TextInput } from 'react-native'; const MyComponent = () => { const inputRef = useRef<TextInput>(null);
useEffect(() => { inputRef.current?.focus(); // 组件挂载后自动聚焦 }, []);
return <TextInput ref={inputRef} placeholder="输入文本" />; }; 代码说明 -useRef 返回一个可变对象 { current: null },不会因组件重新渲染而改变。 -适用于存储 DOM 或组件实例的引用。
2.2 createRef(类组件)
import React, { Component, createRef } from 'react'; import { TextInput, Button, View } from 'react-native'; class MyComponent extends Component { inputRef = createRef<TextInput>();
handleFocus = () => { this.inputRef.current?.focus(); };
render() { return ( <View> <TextInput ref={this.inputRef} placeholder="输入文本" /> <Button title="聚焦输入框" onPress={this.handleFocus} /> </View> ); } } 代码说明:createRef 适用于类组件,每次调用 createRef 都会返回一个新的 ref。
3. refs 的使用场景 -操作原生组件(如 TextInput、ScrollView) -触发组件内部方法(如手动调用 focus()、scrollTo()) -保存状态但不引发重渲染(如存储计时器 ID) -与第三方库集成(如访问原生模块)
4. forwardRef 转发 ref 默认情况下,父组件无法直接获取子组件内部的 ref。 如果要让 ref 透传到子组件,需要使用 forwardRef:
import React, { forwardRef } from 'react'; import { TextInput } from 'react-native';
const MyInput = forwardRef<TextInput, any>((props, ref) => { return <TextInput ref={ref} {...props} />; });
export default MyInput; 代码说明:这样,外部组件就可以直接访问 MyInput 内部的 TextInput 实例
5. refs 的注意事项 -尽量少用 refs,避免过度依赖直接操作 DOM/组件实例。 -不要在 render 过程中修改 ref,ref 应该在 useEffect、event handler 等生命周期方法中使用。 -对于函数式组件,推荐使用 useRef,而不是 createRef
6.总结 -refs 允许我们直接访问组件实例或原生 DOM 组件。 -React Native 中常用于 TextInput、ScrollView 等需要手动控制的组件。 -推荐在函数式组件中使用 useRef,在类组件中使用 createRef。 -forwardRef 允许子组件透传 ref 给内部组件。
|