在 React Native 视图上强制使用 onLayout

Forcing onLayout on React Native view

我有一个包含 Text 字段的 React Native View,我正在使用 onLayout 道具进行一些依赖于它提供的数据的位置计算。

<View onLayout={this.calculateDimensions}>
  <Text>{this.props.content}</Text>
</View>

这很好用,但在某些情况下 content 属性会更新为具有相同字符大小的不同字符串。这导致布局未更改且 onLayout 未触发。

这些位置计算必须在每次 content 道具更新时进行。

注意:我知道有很多方法可以更新组件。更新与布局不同,遗憾的是不会触发 onLayout.

你可以有一个基于内容的唯一键。每当组件的关键属性发生变化时,它都会强制重新渲染。

方法this.calculateDimensions需要有某种指示,它应该被再次调用并重新渲染。我会推荐用于它的状态或备忘录。

让我给你看一个 React Hooks 的例子。我正在设置组件 onLayout,它使用回调 onComponentLayout。 onComponentLayout 具有状态 componentHeight,只要它发生变化就会重新渲染。因此,如果缺少 componentHeight,我可以动态更改它。

...
const onComponentLayout = useCallback(({nativeEvent: {layout}}) => {
   !componentHeight && setComponentHeight(layout.height);
}, [componentHeight, setComponentHeight]);
...

return (
...
    <Component
      onLayout={onComponentLayout}
    />
...
)