我试图用每个按钮播放不同的声音。我尝试从带有传递的索引号的数组变量访问声音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>
    )
  }
}

最佳答案

我想您已经错过了}之后构造函数的结尾piano

您不能在构造函数中声明const变量以供以后通过像this.piano一样访问它时使用它。要了解有关该内容的更多信息,请查看此SO Answer

因此,像对state一样将其声明为变量。

只需将您的const piano = [];更改为this.piano = [];

它应该工作。

09-26 16:19