React Native 函数组件onLayout更新useRef后Text内容不更新如何解决
问题原因
useRef的current属性变更不会触发React组件重新渲染,Text组件渲染时读取的是组件上一次渲染周期的wRef.current快照,因此只会显示初始值0,控制台能打印正确值是因为onLayout回调中读取的是实时的ref值。
解决方案
你的需求仅需要在获取初始布局宽度时触发一次更新,直接使用 useState 存储宽度、新增判断避免重复更新即可,修改后代码如下:
import { useState } from 'react'; // 其余原有导入保持不变 export default function BasicView(props: BasicViewProps): ReactElement { // 使用useState存储需要渲染到UI的宽度值 const [viewWidth, setViewWidth] = useState<number>(0); function onLayout(event: LayoutChangeEvent) { // 已赋值过则直接返回,避免重复触发更新 if (viewWidth !== 0) return; const { width: newWidth } = event.nativeEvent.layout; setViewWidth(newWidth); console.log('viewWidth: ', newWidth); } return ( <View onLayout={onLayout} style={{ width: "100%", justifyContent: "center", alignItems: "center", backgroundColor: "darkgray", }} > <Text style={{ color: "white" }}>{viewWidth}</Text> </View> ); }
如果你的业务逻辑中确实需要保留ref变量用于其他非渲染场景,可以同时使用ref+state,更新时同时给ref.current赋值和触发state更新即可。
内容的提问来源于stack exchange,提问作者Austin Brown
相关产品推荐
相关产品推荐

