> For the complete documentation index, see [llms.txt](https://docs.decentraland.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/2d-ui/ui_button_events.md).

# UI 按钮事件

处理 UI 实体上的按钮事件。

要在 UI 中创建按钮，请创建一个 `Button` UI 元素，并设置以下属性：

* `value`：按钮上显示的文本字符串。
* `onMouseDown`：每次用户在实体上按下指针按钮时运行的回调函数。
* `uiTransform`：UI 元素的位置属性。

以下示例展示了如何创建可点击的 UI 按钮。

***ui.tsx 文件：***

```tsx
import { Button } from '@dcl/sdk/react-ecs'

export const uiMenu = () => (
	<Button
		value="Click me"
		uiTransform={{ width: 100, height: 100 }}
		onMouseDown={() => {
			console.log('Clicked on the UI')
		}}
	/>
)
```

***index.ts 文件：***

```ts
import { ReactEcsRenderer } from '@dcl/sdk/react-ecs'
import { uiMenu } from './ui'

export function main() {
    ReactEcsRenderer.setUiRenderer(uiMenu)
}
```

{% hint style="warning" %}
**📔 注意**：本页后续所有代码片段都假设你有一个 `.ts` 文件，其中运行着类似上述的 `ReactEcsRenderer.setUiRenderer()` 函数。
{% endhint %}

你也可以在 UI 定义外编写点击时执行的函数，并通过名称引用它。这样可以让 UI 代码更易读；如果多个可点击的 UI 实体需要调用同一个函数，这种做法也很有用。

```tsx
import { Button } from '@dcl/sdk/react-ecs'

function handleClick() {
	// Do something onClick
	console.log('Clicked on the UI')
}
export const uiMenu = () => (
	<Button
		value="Click me"
		uiTransform={{ width: 100 }}
		onMouseDown={handleClick}
	/>
)
```

可以向 `Button` UI 元素添加以下字段：

* `onMouseDown`：每次用户在实体上按下指针按钮时运行的回调函数。
* `onMouseUp`：当指针位于实体上方时，每次松开指针按钮都会运行的回调函数。
* `onMouseEnter`：指针每次开始悬停在按钮上时运行的回调函数。
* `onMouseLeave`：指针每次停止悬停在按钮上时运行的回调函数。
* `color`：按钮文本的颜色。
* `font`：按钮文本的字体。
* `textAlign`：按钮内文本的对齐方式
* `uiTransform`：UI 元素的位置属性。
* `uiBackground`：设置 UI 元素的颜色或纹理。
* `variant`：使用此属性将按钮样式设为默认选项之一。 `primary` 和 `secondary` 均可用。
* `disabled`：用于禁用按钮的布尔值。当 `disabled` 设置为 *true*时， `onMouseDown` 和 `onMouseUp` 操作将不再触发，按钮也不会再提示任何指针交互。按钮还会以“灰显”方式绘制：文本和背景的 `alpha` 值都会减半。这仅改变显示效果。场景传入的 `Color4` 值不会被修改，因此你可以放心地在多个元素间重复使用同一个共享调色板对象。

## 按钮样式

将变体设置为 `primary` 或 `secondary` 即可使用按钮的默认样式选项。 `primary` 会将按钮设为红底白字， `secondary` 会将按钮设为白底红字。

```tsx
import { UiEntity, Button, ReactEcs } from '@dcl/sdk/react-ecs'
import { Color4 } from '@dcl/sdk/math'

export const uiMenu = () => (
	<UiEntity
		uiTransform={{
			width: 500,
			height: 230,
			margin: '16px 0 8px 270px',
			padding: 4,
			alignSelf: 'center',
		}}
		uiBackground={{ color: Color4.Gray() }}
	>
		<Button
			value="Click Me"
			variant="primary"
			uiTransform={{ width: 80, height: 20, margin: 4 }}
			onMouseDown={() => {
				console.log('Clicked on the UI')
			}}
		/>
		<Button
			value="Click Me"
			variant="secondary"
			uiTransform={{ width: 80, height: 20, margin: 4 }}
			onMouseDown={() => {
				console.log('Clicked on the UI')
			}}
		/>
	</UiEntity>
)
```

你也可以自由使用背景的所有属性。还可以设置一个变体，然后覆盖其中的某些属性。此示例使用 `primary` 变体，但将颜色覆盖为绿色：

```tsx
import { Button } from '@dcl/sdk/react-ecs'
import { Color4 } from '@dcl/sdk/math'

export const uiMenu = () => (
	<Button
		value="My Button!"
		variant="primary"
		uiTransform={{ width: 100, height: 100 }}
		onMouseDown={() => {
			console.log('Clicked on My Button!')
		}}
		uiBackground={{
			color: Color4.Green(),
		}}
	/>
)
```

## 可切换状态的按钮

一个常见用例是让按钮像开关一样在两种状态之间切换。下面的示例中，每次按下按钮时，颜色都会切换：

```tsx
import { Button } from '@dcl/sdk/react-ecs'
import { Color4 } from '@dcl/sdk/math'

let buttonEnabled = false

export const uiMenu = () => (
	<Button
		value="My Button"
		variant="primary"
		uiTransform={{ width: 100, height: 100 }}
		onMouseDown={() => {
			console.log('Clicked on My Button!')
			buttonEnabled = !buttonEnabled
			if (buttonEnabled) {
				// do something
			} else {
				// do something else
			}
		}}
		uiBackground={{
			color: buttonEnabled ? Color4.Green() : Color4.Red(),
		}}
	/>
)
```

请注意，在上面的示例中，颜色取决于 `buttonEnabled` 变量。每当此变量的值发生变化时，背景颜色都会立即随之改变。

## 悬停反馈

另一个常见用例是在鼠标悬停于按钮上时显示某种视觉提示，以表明该按钮可交互，或者显示说明按钮功能的悬停提示。使用 `onMouseEnter` 和 `onMouseLeave` 回调来检测玩家的光标是否位于按钮上，并做出相应反应。

```tsx
import { Button } from '@dcl/sdk/react-ecs'

let buttonEnabled = false

export const uiMenu = () => (
	<Button
		value="My Button"
		uiTransform={{ width: 100, height: 100 }}
		onMouseDown={() => {
			// button function
		}}
		onMouseEnter={() => {
			// show hint
		}}
		onMouseLeave={() => {
			// hide hint
		}}
	/>
)
```

## 让其他元素可点击

只需为 UI 中的任意元素添加 `onMouseDown` 属性，即可使其变为可点击元素，其工作方式与按钮完全相同。以下示例为背景图像和文本添加了 `onMouseDown` 属性。

```tsx
import { UiEntity, Label, ReactEcs } from '@dcl/sdk/react-ecs'
import { Color4 } from '@dcl/sdk/math'
import { engine, Transform } from '@dcl/sdk/ecs'

export const uiMenu = () => (
	<UiEntity
		onMouseDown={() => {
			console.log('Background clicked!')
		}}
		uiTransform={{
			width: 400,
			height: 230,
		}}
		uiBackground={{ color: Color4.create(0.5, 0.8, 0.1, 0.6) }}
	>
		<Label
			onMouseDown={() => {
				console.log('Label clicked!')
			}}
			value={`Player: ${getPlayerPosition()}`}
			fontSize={18}
			uiTransform={{ width: '100%', height: 30 }}
		/>
	</UiEntity>
)

function getPlayerPosition() {
	const playerPosition = Transform.getOrNull(engine.PlayerEntity)
	if (!playerPosition) return 'unknown'
	const { x, y, z } = playerPosition.position
	return `{x: ${x.toFixed(2)}, y: ${y.toFixed(2)}, z: ${z.toFixed(2)} }`
}
```

## 指针拦截

默认情况下，所有 UI 实体都不会拦截指针事件，这意味着玩家的点击会穿透它们，与其后方 3D 世界中的物体交互。如果某个实体具有 `onMouseDown` 回调，那么它就会拦截指针事件，因此玩家的点击不会影响该 UI 实体后方的内容。

你可以通过更改 `pointerFilter` 属性位于 `uiTransform` 组件上，该组件可添加到任何 UI 实体。例如，要将一个没有 `onMouseDown` 的实体设置为阻挡指针。

支持的 `pointerFilter` 值包括：

* `block`：UI 元素会阻挡指针，玩家无法点击该 UI 元素后方的任何内容。
* `none`：UI 元素不会阻挡指针。该元素不可点击，其后方的任何内容都可以点击。

下面是一个简单的 UI，它没有 `onMouseDown`，但通过将 `pointerFilter` 设为 `block`.

```tsx
import { UiEntity, ReactEcs } from '@dcl/sdk/react-ecs'
import { Color4 } from '@dcl/sdk/math'

// 绘制 UI
export const uiMenu = () => (
	<UiEntity
		uiTransform={{
			width: '100%',
			height: '100px',
			pointerFilter: `block`,
		}}
		uiText={{ value: `此元素会阻挡指针`, fontSize: 40 }}
		uiBackground={{ color: Color4.create(0.5, 0.8, 0.1, 0.6) }}
	/>
)
```

### 阻挡范围取决于布局框，而不是可见像素

阻挡指针的元素会捕获其 **整个矩形区域**内的点击，无论该区域内是否绘制了内容。背景完全透明也不会改变这一点。

{% hint style="danger" %}
**警告：** 切勿在尺寸为 `pointerFilter: 'block'` 的全屏容器上设置指针处理程序或 `100%` 。 `100%`.

它的矩形区域覆盖整个屏幕，因此只要在布局根节点上不慎设置了一个 `onMouseDown` ，其他所有 UI 元素以及 3D 世界中的所有内容都会变得无法点击。UI 看起来仍然完全正常，因为你看到的面板只覆盖屏幕的一小部分，因此很难发现这个问题。
{% endhint %}

只在确实需要处理程序的最小元素上添加处理程序：面板、按钮或行。布局容器不要添加处理程序。

只有两种情况适合使用全屏阻挡元素，而且都需要有意这样设计：

* 一个 **模态框背景层**，用于拦截点击，并且只在模态框打开时渲染。
* 一个 **拖动释放捕获层**，只在拖动过程中存在。请参阅下文的 [拖动交互](#drag-interactions) 。

如果场景中任何位置的点击都失效了，首先就该检查这一点。

## 拖动交互

UI 指针处理程序（`onMouseDown`, `onMouseUp`, `onMouseEnter`, `onMouseLeave`) 不接受任何参数。它们会作为简单的 `() => void` 回调触发，不包含位置或坐标数据。UI 系统中没有 `onMouseDrag` 或 `onMouseMove` 处理程序。

要构建基于拖动的 UI（滑块、拖动条、拖动手柄），请使用 `PrimaryPointerInfo.screenDelta` （来自 `@dcl/sdk/ecs`）。它会提供自上一帧以来鼠标移动的像素数，并且每帧都会更新，不受光标所在位置影响。

实现方式如下：

1. `onMouseDown` 在拖动目标上触发时开始拖动，并记录初始值。
2. 系统每帧读取 `screenDelta` ，并在拖动过程中将其累加到该值中。
3. 带有 `pointerFilter: 'block'` 的全屏透明覆盖层会捕获鼠标释放事件，因此即使在狭窄目标区域之外松开鼠标，也能结束拖动。

```ts
import { engine, PrimaryPointerInfo, UiCanvasInformation } from '@dcl/sdk/ecs'

let dragging = false
let sliderValue = 0.5

// 每帧调用此系统以累加拖动距离
engine.addSystem(() => {
	if (!dragging) return

	const delta = PrimaryPointerInfo.getOrNull(engine.RootEntity)?.screenDelta
	if (!delta || delta.x === 0) return

	// 将屏幕像素转换为 0–1 范围
	// 除以 UI 缩放因子，使拖动速度与光标移动速度一致
	const canvas = UiCanvasInformation.getOrNull(engine.RootEntity)
	const scale = canvas ? Math.min(canvas.width / 1920, canvas.height / 1080) : 1
	const trackWidth = 200 // 滑块轨道的虚拟像素宽度

	sliderValue = Math.max(0, Math.min(1, sliderValue + delta.x / scale / trackWidth))
})
```

{% hint style="warning" %}
**注意：** 在移动设备上， `screenDelta` 始终返回 0（因为没有可自由移动的光标）。若要让滑块兼容移动设备，请在拖动轨道旁添加步进按钮（`-` / `+`）。使用 [`isMobile()`](/creator/content-creator-zh/mian-xiang-yi-dong-duan-gou-jian/kai-fa/detect-platform.md) （来自 `@dcl/sdk/platform` ）来为 UI 添加分支逻辑。
{% endhint %}

{% hint style="info" %}
**提示：** 务必将 `screenDelta` 乘以 UI 缩放系数，否则在分辨率与虚拟尺寸不同的屏幕上，拖动距离就会过长或不足。
{% endhint %}


---

# 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 by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/2d-ui/ui_button_events.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
