Events
Native UI 组件支持 DOM 事件绑定,可将事件监听器绑定到任意 nx-* 组件。组件的事件触发行为遵循浏览器原生 DOM 事件规范,事件回调参数为事件对象。
使用
ts
import { Component } from "@angular/core";
import { NxButton } from "@pc-nexus/angular";
import type { SerialisableEvent } from "@pc-nexus/models";
@Component({
selector: "events-click",
template: ` <nx-button color="primary" (click)="onClick($event)">Save</nx-button> `,
imports: [NxButton],
})
export class EventsClick {
onClick(event: SerialisableEvent) {
console.log(event.type);
}
}tsx
import { NxButton } from "@pc-nexus/react";
import type { SerialisableEvent } from "@pc-nexus/models";
export function EventsClick() {
function onClick(event: SerialisableEvent) {
console.log(event.type);
}
return (
<NxButton color="primary" onClick={onClick}>
Save
</NxButton>
);
}DOM 事件
下表列出了 Native UI 组件支持绑定的 DOM 事件。
- Angular:在模板中使用圆括号绑定事件,绑定语法与原生 DOM 事件一致,例如
(click)="handleClick($event)"。 - React:通过以
on为前缀的属性绑定事件,例如click对应onClick。
| Angular | React | 描述 |
|---|---|---|
(click) | onClick | 单击 |
(dblclick) | onDblclick | 双击 |
(mousedown) | onMousedown | 按下鼠标按键 |
(mouseup) | onMouseup | 松开鼠标按键 |
(focus) | onFocus | 元素获得焦点。元素需要可以聚焦,如按钮、输入框,或设置了 tabindex |
(blur) | onBlur | 元素失去焦点 |
(keydown) | onKeydown | 按下键盘按键。元素需要处于焦点中 |
(keyup) | onKeyup | 松开键盘按键。元素需要处于焦点中 |
(mousemove) | onMousemove | 指针在元素上移动 |
(mouseenter) | onMouseenter | 指针进入元素 |
(mouseleave) | onMouseleave | 指针离开元素 |
(mouseover) | onMouseover | 指针进入元素或其子元素 |
(mouseout) | onMouseout | 指针离开元素或其子元素 |
事件对象
事件回调接收的事件对象遵循浏览器原生 DOM 事件对象的语义,并经过精简,仅包含下表所列字段。
| 名称 | 类型 | 描述 |
|---|---|---|
type | string | 事件名,如 click |
bubbles | boolean | 是否冒泡 |
cancelable | boolean | 是否可取消 |
defaultPrevented | boolean | 是否已取消默认行为 |
eventPhase | number | 事件阶段 |
isTrusted | boolean | 是否由用户操作触发 |
timeStamp | number | 触发时间戳 |
target | object | 触发事件的元素,字段见下表 |
target
| 名称 | 类型 | 描述 |
|---|---|---|
id | string | 元素 id |
tagName | string | 标签名 |
value | string | 当前值。出现在 input、textarea、select、button 上 |
name | string | 原生 name。出现在上述元素上 |
type | string | 原生 type。出现在 input、textarea、button 上 |
checked | boolean | 是否选中。出现在 input 上 |
selectionStart | number | null | 选区起点。出现在 input、textarea 上 |
selectionEnd | number | null | 选区终点。出现在 input、textarea 上 |
target.value 表示触发事件时目标元素的当前值,不代表专门的输入值变更通知。监听组件输入值变化时,请使用组件提供的 valueChange 事件。