> For the complete documentation index, see [llms.txt](https://developers-apps-in-toss.toss.im/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://developers-apps-in-toss.toss.im/documentation/api-and-sdk-zh/react-native/screen-navigation/event.md).

# 屏幕事件

### 1. 返回事件 (`useBackEvent`)

`useBackEvent`是一个 Hook，会返回一个可用于注册和移除返回事件的控制器对象。 `addEventListener`使用它可以注册返回事件， `removeEventListener`使用它可以移除返回事件。只有当用户正在查看该页面时，已注册的返回事件才会生效。页面是否可见是 `useVisibility`为基础。

**签名**

```typescript
function useBackEvent(): BackEventControls;
```

**返回值**

* BackEventControls

  这是一个可以控制返回事件的对象。用于注册事件的 `addEventListener` 方法和用于移除的 `removeEventListener` 方法都包含在内。

**错误**

* Error

  如果这个 Hook `BackEventProvider` 没有在其中使用，会抛出错误。

**示例**

点击“Add BackEvent”按钮后会注册返回事件。之后按返回按钮会弹出“back”提示，并且不会真正返回上一页。点击“Remove BackEvent”按钮后，会移除已注册的事件。之后按返回按钮就会按原有方式返回。

```tsx
import { useEffect, useState } from 'react';
import { Alert, Button, View } from 'react-native';
import { useBackEvent } from '@granite-js/react-native';

function UseBackEventExample() {
  const backEvent = useBackEvent();

  const [handler, setHandler] = useState<{ callback: () => void } | undefined>(undefined);

  useEffect(() => {
    const callback = handler?.callback;

    if (callback != null) {
      backEvent.addEventListener(callback);

      return () => {
        backEvent.removeEventListener(callback);
      };
    }

    return;
  }, [backEvent, handler]);

  return (
    <View>
      <Button
        title="Add BackEvent"
        onPress={() => {
          setHandler({ callback: () => Alert.alert('back') });
        }}
      />
      <Button
        title="Remove BackEvent"
        onPress={() => {
          setHandler(undefined);
        }}
      />
    </View>
  );
}
```

***

### 2. 页面返回事件 (`useWaitForReturnNavigator`)

`useWaitForReturnNavigator`是一个 Hook，帮助你在完成页面切换并返回后，同步执行后续代码。页面跳转是 [@react-navigation/native `useNavigation`中 `navigate`](https://reactnavigation.org/docs/6.x/navigation-prop#navigate)。

例如，当你想记录用户切换到其他页面后又返回时的日志，就会使用它。

**签名**

```typescript
function useWaitForReturnNavigator<T extends Record<string, object | undefined>>(): <RouteName extends keyof T>(
  route: RouteName,
  params?: T[RouteName],
) => Promise<void>;
```

**示例**

点击“移动”按钮后会跳转到其他页面，返回时会留下日志。

```tsx
import { Button } from 'react-native';
import { useWaitForReturnNavigator } from '@apps-in-toss/framework';

function UseWaitForReturnNavigator() {
  const navigate = useWaitForReturnNavigator();

  return (
    <Button
      title="移动"
      onPress={async () => {
        console.log(1);
        await navigate('/examples/use-visibility');
        // 返回到页面后会执行这段代码。
        console.log(2);
      }}
    />
  );
}
```

***

### 3. 可见性事件 (`useVisibility`)

`useVisibility` 使用这个 Hook 可以知道当前页面是否对用户可见。只有当用户正在查看页面时，才可以执行特定操作或记录日志。

当页面对用户可见时 `true`, 不可见时 `false`会返回。只是打开和关闭系统分享弹窗（share）时，值不会改变。

* 切换到其他应用或按下主页按钮时 `false`则返回。
* 再次回到 Toss 应用或页面重新可见时 `true`则返回。
* 当在 Toss 应用内切换到其他服务时 `false`则返回。

**签名**

```typescript
function useVisibility(): boolean;
```

**返回值**

* boolean

  表示当前页面是否对用户可见。

**示例**

切换到主页时 `false`false `true`true`https://toss.im`）时 `false`false `true`false

```tsx{1,6,8-12}
import { useVisibility } from '@granite-js/react-native';
import { useEffect } from 'react';
import { Button, Linking } from 'react-native';

export default function VisibilityPage() {
  const visibility = useVisibility();

  useEffect(() => {
    console.log({
      visibility,
    });
  }, [visibility]);

  return (
    <Button
      onPress={() => {
        Linking.openURL('https://toss.im');
      }}
      title="跳转到 https://toss.im"
    />
  );
}

/**
 * 输出示例：
 * { "visibility": false }
 * { "visibility": true }
 * { "visibility": false }
 * { "visibility": true }
 */
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://developers-apps-in-toss.toss.im/documentation/api-and-sdk-zh/react-native/screen-navigation/event.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
