有许多原生的媒体空间,都支持 开始、暂停、重置、获取进度等控制播放的状态方法,例如视频、音频等。
我们可以在组件内部实现这些控制方法,然后通过 ref 传递给父组件,父组件就可以通过 ref 调用这些方法来控制媒体播放
在下面的案例中,我模拟了一个支持这些方法的定时器播放器。并结合 ref 与 useImperativeHandle 进行封装,大家直接看代码学习
需要注意:本案例抛弃了 forwardRef 的使用,直接使用 useImperativeHandle 来实现 ref 的传递
01import { useRef } from 'react';02import { Chronograph, ChronographHandle } from './chronograph';0304export default function Demo01() {05const chronoRef = useRef<ChronographHandle>(null);0607function __clickHandler(method: string) {08const methodName = method.toLowerCase() as keyof ChronographHandle;09chronoRef.current?.[methodName]();10}1112return (13<div className="p-4">14<div className="max-w-2xl mx-auto space-y-2">15<Chronograph ref={chronoRef} label="一个自定义的计时器" />16<div className="grid grid-cols-3 gap-px">17{(['START', 'STOP', 'RESET']).map((label) => (18<button19key={label}20onClick={() => __clickHandler(label)}21className="button"22>{label}</button>23))}24</div>25</div>26</div>27);28}