1
- import React , { Component } from 'react'
1
+ import { useEffect , useRef , type FC } from 'react'
2
2
import classNames from 'classnames'
3
3
import './PlayerLyric.module.less'
4
4
import styles from './PlayerLyric.module.less'
@@ -11,42 +11,41 @@ interface PlayerLyricProps {
11
11
toggleIsTouching ( ...args : unknown [ ] ) : unknown ;
12
12
}
13
13
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
+ }
50
24
}
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
+ )
51
50
}
52
51
export default PlayerLyric
0 commit comments