首页 > 解决方案 > 布局上的组件文本内容更新

问题描述

我正在使用 Typescript,并且我有这个(功能性)React Native 组件:

export default function BasicView(props: BasicViewProps): ReactElement {
  const wRef = useRef<number>(0);

  function onLayout(event: LayoutChangeEvent) {
    const {width} = event.nativeEvent.layout;
    wRef.current = width;
    console.log('wRef: ' + wRef.current);
  }

  return (
    <View
      onLayout={onLayout}
      style={{
        width: "100%",
        justifyContent: "center",
        alignItems: "center",
        backgroundColor: "darkgray",
      }}
    >
      <Text style={{ color: "white" }}>{wRef.current}</Text>
    </View>
  );
}

一切似乎都在使用我的onLayout代码。我的问题是组件中的内容<Text/>(打算打印出来wRef.current)没有更新;当前0已打印并且永远不会更改。我想我部分理解为什么它没有更新,但我的问题是如何让它更新为wRef.current?

对于它的价值,我不打算频繁更新这个组件,但我只需要一次更新即可获得 View 布局宽度的初始值。

标签: typescriptreact-native

解决方案


我已经尝试过了,它似乎正在工作

export default function App() {
  const wRef = React.useRef(0);
const [width, setwidth] = React.useState("")
  function onLayout(event: LayoutChangeEvent) {
    const {width} = event.nativeEvent.layout;
    wRef.current = width;
    setwidth(width)
    console.log('wRef: ' + wRef.current);
  }

  return (
    <View
      onLayout={onLayout}
      style={{
        width: "100%",
        justifyContent: "center",
        alignItems: "center",
        backgroundColor: "darkgray",
      }}
    >
      <Text style={{ color: "white" }}>{width}</Text>
    </View>
  );
}

关于您的问题,我从未尝试过打印 ref 值,但您的问题看起来像是关于状态的初始值,我已经通过更新额外的 useState 来解决此类问题,只是为了更新状态。


推荐阅读