使用了rc-danmaku
组件地址: 查看地址
本身不支持loop循环弹出, 结合组件内置的方法和hooks特性实现了 弹幕加载完成重复渲染
主要用到的方法有 onBulletOut、danmakuIns.getRestAmount()、push
实现过程:
import React, { useEffect, useRef, useState } from 'react';
import Danmaku from 'rc-danmaku';
// dataSource 弹幕数据, 从父组件获取
const TestDanmaku: React.FC = ({ dataSource }) => {
const danmakuInsRef = useRef(null);
const [count, setCount] = useState(0);
// 弹幕一次性全部发送方法
const renderDanmaku = () => {
// console.log('====renderDanmaku out====');
if (dataSource.length > 0) {
dataSource.map((item) => {
const text = item.nickName + ':' + item.content;
const textDom = { fontSize: '16px' }}>{text};
danmakuInsRef.current.push(textDom);
});
}
};
useEffect(() => {
const danmakuIns = new Danmaku('.danmaku-wrapper', {
maxRow: 0,
rowHeight: 32,
onBulletOut() {
// 关键代码, 弹幕消失时计算弹幕队列中剩余的数量
// console.log('====bullet out====', danmakuIns.getRestAmount());
setCount(danmakuIns.getRestAmount());
},
onQueueRunOut() {
// setCount(danmakuIns.getRestAmount());
// console.log('====queue run out====', danmakuIns.getRestAmount());
},
});
danmakuInsRef.current = danmakuIns;
}, []);
useEffect(() => {
setTimeout(() => {
// 延时避免字体重叠
renderDanmaku();
}, 500);
}, [dataSource]);
useEffect(() => {
if (danmakuInsRef.current) {
// 当剩余数为0时再次发送弹幕
(count === 0 && dataSource.length) && setTimeout(() => {
renderDanmaku();
}, 1000);
}
// console.log('out', count)
}, [count]);
return (
{
width: '100%',
height: '96px',
backgroundColor: '#fff',
marginTop: '10px',
}}
/>
{/* */}
);
};
export default TestDanmaku;
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84