Skip to content

Commit 78cd13f

Browse files
committed
fix(react-vite): fix scrolling lyric causing error bug
1 parent d140cbc commit 78cd13f

File tree

1 file changed

+36
-37
lines changed

1 file changed

+36
-37
lines changed
Lines changed: 36 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import React, { Component } from 'react'
1+
import { useEffect, useRef, type FC } from 'react'
22
import classNames from 'classnames'
33
import './PlayerLyric.module.less'
44
import styles from './PlayerLyric.module.less'
@@ -11,42 +11,41 @@ interface PlayerLyricProps {
1111
toggleIsTouching(...args: unknown[]): unknown;
1212
}
1313

14-
class PlayerLyric extends Component<PlayerLyricProps> {
15-
constructor(props) {
16-
super(props)
17-
this.lyricsRef = []
18-
}
19-
componentDidUpdate() {
20-
const { prevLyricIndex } = this.props
21-
this.lyricsRef[prevLyricIndex] &&
22-
this.lyricsRef[prevLyricIndex].current.scrollIntoView()
23-
}
24-
render() {
25-
this.lyricsRef = []
26-
const { lyrics, prevLyricIndex, toggleIsTouching } = this.props
27-
return (
28-
<div
29-
className={styles.PlayerLyric}
30-
onTouchStart={() => toggleIsTouching(true)}
31-
onTouchEnd={() => toggleIsTouching(false)}
32-
>
33-
{lyrics.map((lyric, index) => {
34-
const lyricRef = React.createRef()
35-
this.lyricsRef.push(lyricRef)
36-
return (
37-
<p
38-
key={index}
39-
ref={lyricRef}
40-
className={classNames(styles.PlayerLyric_text, {
41-
[styles['PlayerLyric_text--active']]: index === prevLyricIndex + 1
42-
})}
43-
>
44-
{lyric.text}
45-
</p>
46-
)
47-
})}
48-
</div>
49-
)
14+
const PlayerLyric: FC<PlayerLyricProps> = ({ lyrics, prevLyricIndex, toggleIsTouching }) => {
15+
const lyricElementsRef = useRef<(HTMLParagraphElement | null)[]>([]);
16+
const setLyricElement = (
17+
index: number,
18+
element: HTMLParagraphElement | null
19+
) => {
20+
lyricElementsRef.current[index] = element
21+
return () => {
22+
lyricElementsRef.current.splice(index, 1)
23+
}
5024
}
25+
useEffect(() => {
26+
lyricElementsRef.current[prevLyricIndex]?.scrollIntoView();
27+
}, [prevLyricIndex]);
28+
29+
return (
30+
<div
31+
className={styles.PlayerLyric}
32+
onTouchStart={() => toggleIsTouching(true)}
33+
onTouchEnd={() => toggleIsTouching(false)}
34+
>
35+
{lyrics.map((lyric, index) => {
36+
return (
37+
<p
38+
key={index}
39+
ref={el=>setLyricElement(index, el)}
40+
className={classNames(styles.PlayerLyric_text, {
41+
[styles['PlayerLyric_text--active']]: index === prevLyricIndex + 1
42+
})}
43+
>
44+
{lyric.text}
45+
</p>
46+
)
47+
})}
48+
</div>
49+
)
5150
}
5251
export default PlayerLyric

0 commit comments

Comments
 (0)