useButton

预计阅读时间: 3 分钟

创建可访问按钮组件的钩子,提供键盘激活和无障碍检查。

useButton 钩子用于创建符合 Video.js 标准的可访问按钮组件。它提供键盘激活支持(Enter 和 Space 键)以及 ARIA 属性处理,确保按钮组件在所有设备上都能正常工作。

示例

基本用法

import { useButton } from '@videojs/react';

function MyButton({ onClick, children }) {
  const { buttonProps, buttonRef } = useButton({
    onClick,
  });

  return (
    <button {...buttonProps} ref={buttonRef}>
      {children}
    </button>
  );
}

自定义标签

import { useButton } from '@videojs/react';
import { renderElement } from '@videojs/react';

function IconButton({ icon, label, onClick }) {
  const { buttonProps } = useButton({
    onClick,
    label,
  });

  return renderElement({
    element: 'button',
    className: 'vjs-icon-button',
    props: {
      ...buttonProps,
      'aria-label': label,
    },
    render: () => (
      <span className="vjs-icon-placeholder" aria-hidden="true">
        {icon}
      </span>
    ),
  });
}

禁用状态

import { useButton } from '@videojs/react';

function DisabledButton({ onClick, disabled }) {
  const { buttonProps } = useButton({
    onClick,
    isDisabled: disabled,
  });

  return (
    <button {...buttonProps} disabled={disabled}>
      Click me
    </button>
  );
}

API 参考

参数

参数类型默认值说明
paramsUseButtonParams按钮配置参数

UseButtonParams

参数类型默认值说明
onClick() => void点击事件处理函数
isDisabledbooleanfalse是否禁用按钮
labelstring按钮标签(用于无障碍)
trackStateobject用于计算禁用状态的追踪状态

返回值

返回值类型说明
getButtonProps(props?: object) => ButtonProps获取按钮 props 的函数,支持合并额外 props
buttonRefRefObject<HTMLElement>按钮元素的 ref

ButtonProps

属性类型说明
onKeyDownReact.KeyboardEventHandler键盘事件处理(支持 Enter 和 Space)
onClickReact.MouseEventHandler点击事件处理
tabIndexnumberTab 键顺序(禁用时为 -1)
rolestringARIA 角色("button")
aria-disabledbooleanARIA 禁用状态

功能特性

键盘激活

useButton 自动处理键盘激活:

  • Enter 键:触发 onClick
  • Space 键:触发 onClick 并阻止页面滚动
  • 当按钮被 isDisabled 禁用时,键盘事件不会触发

无障碍支持

  • 自动设置 role="button"
  • 处理 aria-disabled 状态
  • 管理 tabIndex 以支持键盘导航
  • isDisabled 为 true 时,tabIndex 设置为 -1

Props 组合

getButtonProps 函数允许合并额外的 props:

const { getButtonProps } = useButton({ onClick });

<button 
  {...getButtonProps({ 'data-custom': 'value' })}
  className="my-button"
>
  Click me
</button>

参见