You need to enable JavaScript to run this app. react-sound组件ref未生效 页面加载报url、playStatus等必填prop为undefined错误
优惠活动
大模型
产品
解决方案
定价
更多

react-sound组件ref未生效 页面加载报url、playStatus等必填prop为undefined错误

问题原因
  • react-sound的url、playStatus均为必填prop,必须在组件渲染时通过JSX属性传入,你在首次渲染<Sound />时没有传入这两个参数,自然触发PropType校验报错。
  • React组件的prop为只读属性,通过ref直接修改组件实例属性的写法是无效的,既不会触发组件重新渲染,也不会被组件内部逻辑识别,所以你通过ref设置的所有配置都没有生效。
  • 违反了React Hook的调用规则:Hook不允许放在条件判断语句内,你将useEffect写在if(props.state)的分支中,会导致Hook调用顺序不稳定,引发逻辑异常。
解决方案

直接将所有react-sound需要的配置都作为prop传入,删除ref修改属性的逻辑,调整Hook调用位置符合规范即可,修正后代码如下:

import { useState } from 'react'
import Sound from 'react-sound'

function AudioButton(props) {
  const 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) {
  return <Sound
    url='/sounds/ambientStereoSound.wav'
    autoLoad={true}
    loop={true}
    volume={100}
    playStatus={props.state ? Sound.status.PLAYING : Sound.status.PAUSED}
  />
}

export default function PlayAmbientSound() {
  const [audioState, setAudioState] = useState(false)
  return (
    <>
      <AmbientSound state={audioState} />
      <AudioButton state={audioState} onClick={() => setAudioState(!audioState)} />
    </>
  )
}

内容的提问来源于stack exchange,提问作者Defgun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 06:06:03