我试图用每个按钮播放不同的声音。我尝试从带有传递的索引号的数组变量访问声音url
我用playSound函数中的键传递索引号,然后尝试从const piano变量获取url,这会在控制台中引发错误。我在这里做错了什么?
let { Button, ButtonToolbar, ButtonGroup, Radio, DropdownButton, MenuItem } = ReactBootstrap;
class App extends React.Component {
constructor(props){
super(props);
this.state = {
power: true,
instrument: 'piano',
buttonColor:true,
};
this.playSound = this.playSound.bind(this);
this.toggle = this.toggle.bind(this);
this.changeColor =this.changeColor.bind(this);
const piano = [{
keyCode: 81,
keyTrigger: 'Q',
id: 'Heater-1',
url: 'https://s3.amazonaws.com/freecodecamp/drums/Heater-1.mp3'
}, {
keyCode: 87,
keyTrigger: 'W',
id: 'Heater-2',
url: 'https://s3.amazonaws.com/freecodecamp/drums/Heater-2.mp3'
}, {
keyCode: 69,
keyTrigger: 'E',
id: 'Heater-3',
url: 'https://s3.amazonaws.com/freecodecamp/drums/Heater-3.mp3'
},
];
changeColor(){
this.setState({buttonColor: !this.state.buttonColor})
}
playSound(key){
if (this.state.power == true) {
this.audio = new Audio(this.piano[key].url)
this.audio.play();
this.changeColor();
setTimeout(() => this.changeColor(), 200 )
}
};
toggle() {
this.setState({
power: !this.state.power,
});
console.log(!this.state.power)
};
render(){
let btn_style = this.state.buttonColor ? 'primary' : 'warning'
return(
<div id='container' >
<div className='buttons' >
<div className='firstLine'>
<ButtonToolbar>
<Button bsStyle= {btn_style} className='drum-pad' bsSize="large" onClick = {() => this.playSound(0)} >Q</Button>
<Button bsStyle= {btn_style} className='drum-pad' bsSize="large" onClick = {() => this.playSound(1)} >W</Button>
<Button bsStyle="primary" className='drum-pad' bsSize="large">E</Button>
</ButtonToolbar>
</div>
</div>
</div>
)
}
}
答案 0 :(得分:2)
我想您在}
之后错过了构造函数的结尾piano
。
您无法在构造函数中声明const变量,以稍后通过像this.piano
那样访问它来使用它。要了解有关该信息的更多信息,请查看此SO Answer。
因此,像对state
一样,将其声明为变量。
只需将您的const piano = [];
更改为this.piano = [];
。
应该可以。