当我点击播放按钮时,它显示一个错误:
'无法读取空的属性'play'
这是我的代码:
import React, {useState} from 'react';
import ReactDOM from 'react-dom';
const App = () => {
const player = document.getElementById('player')
const [musicIndex, setMusicIndex] = useState(0);
const musicArray = [
{
title: 'koe no katachi',
link: 'aiko- 恋をしたのはmusic video.mp3'
},
{
title: 'stay alive',
link: 'ReZero ED Ending 2 FullEmilia (Rie Takahashi) - Stay AliveENG Sub.mp3'
},
{
title: 'Tenshi ni fureta',
link: '[K-ON AMV] 天使にふれたよ.mp3'
}
]
return (
<div className="spotify-clone">
<audio id='player' className='player' src={`Songs/${musicArray[musicIndex].link}`} controls></audio>
<h3>{musicArray[musicIndex].link}</h3>
<div className='button'>
<button onClick={() => setMusicIndex(musicIndex + 1)}>Next</button>
<button onClick={() => setMusicIndex(musicIndex - 1)}>Prev</button>
<button onClick={() => player.play()}>Play</button>
<button onClick={() => player.pause()}>Pause</button>
</div>
</div>
);
}
ReactDOM.render(<App />, document.getElementById('music-player'));
您需要使用ref
import React, {useState,useRef} from 'react';
export const App = () => {
const playerRef = useRef<HTMLAudioElement>(null);
const [musicIndex, setMusicIndex] = useState(0);
const musicArray = [
{
title: 'koe no katachi',
link: 'aiko- 恋をしたのはmusic video.mp3'
},
{
title: 'stay alive',
link: 'ReZero ED Ending 2 FullEmilia (Rie Takahashi) - Stay AliveENG Sub.mp3'
},
{
title: 'Tenshi ni fureta',
link: '[K-ON AMV] 天使にふれたよ.mp3'
}
]
return (
<div className="spotify-clone">
<audio id='player' ref={playerRef}
className='player'
src={`Songs/${musicArray[musicIndex].link}`} controls>
</audio>
<h3>{musicArray[musicIndex].link}</h3>
<div className='button'>
<button onClick={() => setMusicIndex(musicIndex + 1)}>Next</button>
<button onClick={() => setMusicIndex(musicIndex - 1)}>Prev</button>
<button onClick={() => playerRef?.current?.play()}>Play</button>
<button onClick={() => playerRef?.current?.pause()}>Pause</button>
</div>
</div>
);
}
您可以尝试初始化播放器内联:
<button onClick={() => document.getElementById('player').play()}>Play</button>
我不知道这是否有助于
此处不应使用document.getElementById
,因为此时尚未创建DOM。因此,与其这样做,不如使用useState声明一个新变量:const [player, setPlayerValue] = useState('');
然后在useEffect方法中用CCD_ 3设置玩家变量的值。