React Navigation v6: 如何检测屏幕获得或失去焦点?

huangapple go评论72阅读模式
英文:

React Navigation v6: How to detect when screen comes into or out of focus?

问题

在React Navigation v4中,您可以将您的组件包装在withNavigationFocus()中,然后使用以下方式触发函数:

componentDidUpdate(prevProps) {
  if (!prevProps.isFocused && this.props.isFocused) {
    ...
  }
}

在React Navigation v6中是否有类似的方法?我看到的只是您可以使用useIsFocused()来检测屏幕当前是否处于焦点状态,但无法检测何时刚刚进入/退出焦点。

英文:

In React Navigation v4, you could wrap your component in withNavigationFocus() and then trigger a function using

componentDidUpdate(prevProps) {
  if (!prevProps.isFocused && this.props.isFocused) {
    ...
  }
}

Is there a way to do this in React Navigation v6? All I've seen is that you can use useIsFocused() to detect if the screen is currently focused, but not to detect when it's just come into / out of focus.

答案1

得分: 3

使用useFocusEffect在屏幕聚焦时运行副作用。

useFocusEffect类似于React的useEffect钩子。唯一的区别是它仅在屏幕当前处于焦点状态时运行。

useFocusEffect(
  React.useCallback(() => {
    // 当屏幕处于焦点时执行某些操作
    return () => {
      // 当屏幕不再处于焦点时执行某些操作
    };
  }, [])
);
英文:

Use useFocusEffect to run side-effects when a screen is focused.

> The useFocusEffect is analogous to React's useEffect hook. The only difference is that it only runs if the screen is currently focused.

useFocusEffect(
  React.useCallback(() => {
    // Do something when the screen is focused
    return () => {
      // Do something when the screen is unfocused
    };
  }, [])
);

huangapple
  • 本文由 发表于 2023年5月21日 11:01:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76298115.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定