代码之家  ›  专栏  ›  技术社区  ›  sinan

react-未捕获类型错误:无法读取未定义的属性“1”

  •  0
  • sinan  · 技术社区  · 6 年前

    我试着用每个按钮播放不同的声音。我尝试从数组变量中访问声音的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>
        )
      }
    }
    1 回复  |  直到 6 年前
        1
  •  2
  •   SkrewEverything    6 年前

    } piano

    this.piano SO Answer

    state

    const piano = []; this.piano = [];