> 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="添加 BackEvent"
        onPress={() => {
          setHandler({ callback: () => Alert.alert('back') });
        }}
      />
      <Button
        title="移除 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 App 或页面重新可见时 `true`会返回。
* 切换到 Toss App 内的其他服务时 `false`会返回。

**签名**

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

**返回值**

* boolean

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

**示例**

跳转到主页时 `false`会被记录，返回时 `true`会被记录。外部链接（`https://toss.im`）时跳转会被记录。 `false`会被记录，返回时 `true`会被记录。

```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.
