useContainerAttach
预计阅读时间: 3 分钟
注册自定义容器元素的钩子。
useContainerAttach 用于在 Video.js React 中注册自定义的容器元素。当你想替换默认的 Player.Container 组件时,这个钩子允许你将自己的容器元素注册到播放器上下文中。
示例
基本用法
import { useContainerAttach } from '@videojs/react';
function CustomContainer({ children, className }) {
const setContainer = useContainerAttach();
return (
<div
ref={setContainer}
className={`custom-container ${className || ''}`}
>
{children}
</div>
);
}
在 Provider 中使用
import { useContainerAttach } from '@videojs/react';
function MyCustomContainer({ children }) {
const setContainer = useContainerAttach();
return (
<div
ref={setContainer}
className="vjs-custom-container"
role="region"
aria-label="Video player"
>
{children}
</div>
);
}
function App() {
return (
<Player.Provider>
<Player.Container>
<Video src="https://example.com/video.mp4" />
<Controls />
</Player.Container>
</Player.Provider>
);
}
API 参考
返回值
| 返回值 | 类型 | 说明 |
|---|
Dispatch<RefObject<HTMLElement>> | React.RefCallback<HTMLElement> | 设置器函数,用于注册容器元素 |
返回值详解
返回的函数是一个 RefCallback,当你将其附加到 DOM 元素时,该元素会自动注册为播放器容器。
类型签名:
type Dispatch = React.RefCallback<HTMLElement>
使用场景
何时需要
useContainerAttach 主要在以下场景使用:
- 替换 Player.Container - 当你想使用自定义的容器组件而不是默认的
Player.Container
- 自定义布局 - 需要完全控制播放器容器的结构和样式
- 集成第三方组件 - 将 Video.js React 与其他需要容器引用的库集成
安全使用
这个钩子可以安全地在 Player.Provider 外部调用:
function SafeComponent() {
const setContainer = useContainerAttach();
// 在 Provider 外调用会返回 undefined
// 不会抛出错误
return <div ref={setContainer}>Content</div>;
}
当在 Provider 外调用时,返回值为 undefined,但不会抛出错误。这意味着你的组件可以在 Provider 内外的任何位置渲染。
与 useMediaAttach 的区别
| 钩子 | 用途 | 何时使用 |
|---|
useContainerAttach | 注册容器元素 | 替换 Player.Container 时 |
useMediaAttach | 注册媒体元素 | 替换 Video/Audio 组件时 |
参见