You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 15:45:06