reactjs - 为什么我的“音频按钮”不播放声音(onClick)
问题描述
我正在努力找出为什么当我单击它时我的按钮不发出声音。console.log() 测试工作正常,但 -part 不行。我也尝试了一些 npm-packets 来解决这个问题,但我的代码似乎有一个普遍的问题。它出什么问题了?有人能帮我吗?
main.js :
import Button from './button';
class Drumpad extends Component {
constructor(props) {
super(props);
this.state = {
Q:
{
id: 'Q',
name: 'Q',
src: 'https://s3.amazonaws.com/freecodecamp/drums/Heater-1.mp3'
},
}
}
render() {
return (
<div style={test}>
<div id='row1'>
<Button cfg={this.state.Q}/>
</div>
</div>
)
}
}
还有 button.js:
class Button extends Component {
constructor(props) {
super(props);
this.state = {
}
}
handleClick = () => {
console.log(this.props.cfg.src);
return (
<audio ref='audioClick' src={this.props.cfg.src} type='audio/mp3' autoPlay>
);
};
render() {
return (
<div>
<button style={buttonStyle} onClick={this.handleClick}>
<h1>{this.props.cfg.name}</h1>
</button>
</div>
)
}
}
解决方案
中的handleClick
方法button.js
返回一个<audio>
元素,这是多余的,因为您想播放声音onClick
。
相反,我使用Audio
构造函数来创建音频剪辑的实例,使用作为道具提供的 url,我将其设置为 state。
然后我使用回调来调用play()
它的方法。
handleClick = () => {
const audio = new Audio(this.props.cfg.src);
this.setState({ audio }, () => {
this.state.audio.play();
});
};
所以你button.js
变成了这样的东西:
import React, { Component } from "react";
const buttonStyle = {};
export default class Button extends Component {
constructor(props) {
super(props);
this.state = {
audio: false
};
}
handleClick = () => {
console.log(this.props.cfg.src);
const audio = new Audio(this.props.cfg.src);
this.setState({ audio }, () => {
this.state.audio.play();
});
};
render() {
return (
<div>
<button style={buttonStyle} onClick={this.handleClick}>
<h1>{this.props.cfg.name}</h1>
</button>
</div>
);
}
}
你的main.js
遗体保持原样。
这是一个有效的代码框。
推荐阅读
- python - 如何在 python 中使用 xlsxwriter 创建 log(x) 图?
- javascript - Qualtrics:如何将管道文本叠加到图像/图形上?
- python - 关于神经网络激活函数的困惑
- sql - 如何过滤掉表中的不同对?
- typescript - NestJs TypeORM 异步配置
- c++ - 如何修复以代码 2 退出的“CL.exe”
- python - VI_ERROR_TMO (-1073807339): 操作完成前超时
- java - 复杂聚合
- ios - 如何在 iOS Storekit 中使用多个捆绑包 ID
- c# - PHP 使用 c# DLL 参数类型问题