You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中HTML audio元素无法读取传递的URL源问题求助

问题:React中audio的source无法获取props传递的URL?

我正在CodePen上使用React开发一个鼓垫组件,但在将props传递给HTML audio元素的source子元素时,发现该元素无法获取到音频文件的链接。当我直接将URL替换掉props.audioSource的位置时,功能就能正常运行。这是否是React的特性导致无法给HTML audio元素传递URL?


问题原因与解决方案

这不是React的特性限制,问题出在你错误地使用了JSX属性赋值语法:

  • 在JSX中,动态属性值不需要用"{}"包裹成字符串,直接写{变量名}即可。你当前的写法会把"{props.audioSource}"当成字面量字符串传递,而非解析props中的真实音频链接。
  • 同时你在div的className、id,以及audio的id上也存在同样问题:比如className=".drum-pad"会把类名设置成带点号的.drum-pad,正确写法是className="drum-pad";id="{props.drumPadId}"会把id设置成字符串"{props.drumPadId}",正确写法是id={props.drumPadId}。

修正后的代码

const DrumTileComponent = (props) => {
  return (
    <div className="drum-pad" id={props.drumPadId}>
      <div> 
        <audio className="clip" id={props.drumPadId} controls> 
          <source src={props.audioSource} type="audio/mp3" />
          Your browser does not support the audio element.
        </audio>
      </div>
    </div>
  );
};

const DisplayComponent = (props) => {
  return (
    <div id="display">
      
    </div>
  );
};

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      
    }
  }
  
  render() {
    return (
      <div id="drum-machine">
        <DrumTileComponent drumPadId="A" audioSource="https://s3.amazonaws.com/freecodecamp/drums/Heater-1.mp3" />
        Hello
      </div>
    );
  };
};
ReactDOM.render(<App />, document.getElementById("App"));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 23:45:40