Reactjs Ref不适用于反应声音
在pageload上,我得到错误信息: 失败的道具类型:道具Reactjs Ref不适用于反应声音,reactjs,react-hooks,Reactjs,React Hooks,在pageload上,我得到错误信息: 失败的道具类型:道具url在Sound中标记为所需,但其值为未定义 失败的道具类型:道具播放状态在声音中标记为所需,但其值为未定义 基本上,名为“sound”的ref的所有属性都不会应用于soundobject import { useEffect, useRef, useState } from 'react' import Sound from 'react-sound' function AudioButton(props) { let
url
在Sound
中标记为所需,但其值为未定义
失败的道具类型:道具播放状态
在声音
中标记为所需,但其值为未定义
基本上,名为“sound”的ref的所有属性都不会应用于soundobject
import { useEffect, useRef, useState } from 'react'
import Sound from 'react-sound'
function AudioButton(props) {
let buttonText = props.state ? 'Turn audio off' : 'Turn audio on'
return (
<button onClick={props.onClick}
className='absolute bottom-0 right-0 z-10 flex items-center justify-center p-3 m-3 text-white transition-colors ease-in-out bg-blue-600 rounded-md cursor-pointer duration-350 hover:bg-blue-800'
>
{buttonText}
</button>
)
}
function AmbientSound(props) {
const sound = useRef()
useEffect(() => {
sound.current.url='/sounds/ambientStereoSound.wav'
sound.current.autoLoad=true
sound.current.loop=true
sound.current.volume=100
}, [])
if(props.state){
useEffect(() => {
sound.current.playStatus=Sound.status.PLAYING
})
}else{
useEffect(() => {
sound.current.playStatus=Sound.status.PAUSED
}, [props.state])
}
return <Sound ref={sound} />
}
export default function PlayAmbientSound() {
const [audioState, setAudioState] = useState(false)
return (
<>
<AmbientSound state={audioState} />
<AudioButton state={audioState} onClick={() => setAudioState(!audioState)} />
</>
)
}
从'react'导入{useffect,useRef,useState}
从“反应声音”导入声音
功能音频按钮(道具){
let buttonText=props.state?“关闭音频”:“打开音频”
返回(
{buttonText}
)
}
功能环境声音(道具){
const sound=useRef()
useffect(()=>{
sound.current.url='/sounds/ambient立体声.wav'
sound.current.autoLoad=true
sound.current.loop=true
声音、电流、音量=100
}, [])
如果(道具状态){
useffect(()=>{
sound.current.playStatus=sound.status.PLAYING
})
}否则{
useffect(()=>{
sound.current.playStatus=sound.status.PAUSED
},[props.state])
}
返回
}
导出默认函数PlayAmbientSound(){
常量[audioState,setAudioState]=useState(false)
返回(
setAudioState(!audioState)}/>
)
}
失败的道具类型错误是由于没有将正确的道具传递给声音组件造成的
如果查看,可以看到分配给ref.current
的值可以作为道具传递给组件:
// In your React component:
render() {
return (
<Sound
url="cool_sound.mp3"
playStatus={Sound.status.PLAYING}
playFromPosition={300 /* in milliseconds */}
onLoading={this.handleSongLoading}
onPlaying={this.handleSongPlaying}
onFinishedPlaying={this.handleSongFinishedPlaying}
/>
);
}
//在React组件中:
render(){
返回(
);
}
如果您将这些值作为道具传递,而不是将它们分配给ref,您应该会看到这些警告消失。以下是您可以传递到的道具的完整列表:根据pat的解决方案,我将代码更改为:
function AmbientSound(props) {
let state = ''
if(props.state){
state = Sound.status.PLAYING
}else{
state = Sound.status.PAUSED
}
return (
<Sound
url='/sounds/ambientStereoSound.wav'
autoLoad={true}
playStatus={state}
loop={true}
volume={100}
/>
)
}
功能环境声音(道具){
让状态=“”
如果(道具状态){
状态=声音、状态、播放
}否则{
state=Sound.status.PAUSED
}
返回(
)
}