2

我是新手,反應/反應本地,並試圖構建一個播放本地MP3的簡單應用程序。我正在使用react-native-sound模塊,它似乎工作得很好。React Native:使用const中的道具

雖然現在,我試圖通過fileName作爲從我的類別道具球員組成。 這似乎是react-native-sound需要我預先加載一個聲音文件。因此,現在我得到以下錯誤:

"Unhandled JS Exception: Cannot read property 'fileName' of undefined".

...  
import Sound from 'react-native-sound'; 

const play = new Sound(this.props.fileName, Sound.MAIN_BUNDLE, (error) => { 
    if (error) { 
    console.log('failed to load the sound', error); 
    } else { // loaded successfully 
    console.log('duration in seconds: ' + play.getDuration() + 
     'number of channels: ' + play.getNumberOfChannels()); 
    } 
}); 

export default class playTrack extends Component { 
    constructor(props) { 
     super(props); 
     this.state = { 
     playing: false, 
     track: this.props.fileName, 
     }; 
    } 

    playTrack() { 
     this.setState({playing: true}) 
     play.play((success) => { 
     if (success) { 
      console.log('successfully finished playing'); 
     } else { 
      console.log('playback failed due to audio decoding errors'); 
     } 
     }) 
    } 
... 

你有任何指針,我如何去了解呢?

+1

在組件類定義之外沒有'this.props'。 – pawel

+1

在第三行中,您使用this.props.filename約定'Sound',但'this'指向窗口並且沒有道具 – MichaelB

+1

詞法範圍;} – jdmdevdotnet

回答

2

您無法以您嘗試使用它的方式從課程外部訪問班級實例的this。相反,在構造函數中創建Sound

import Sound from 'react-native-sound'; 

export default class playTrack extends Component { 
    constructor(props) { 
     super(props); 

     this.play = new Sound(props.fileName, Sound.MAIN_BUNDLE, (error) = > { 
      if (error) { 
       console.log('failed to load the sound', error); 
      } else { // loaded successfully 
       console.log('duration in seconds: ' + this.play.getDuration() + 
        'number of channels: ' + this.play.getNumberOfChannels()); 
      } 
     }); 

     this.state = { 
      playing: false, 
      track: this.props.fileName, 
     }; 
    } 

    playTrack() { 
     this.setState({ 
      playing: true 
     }) 
     this.play.play((success) = > { 
      if (success) { 
       console.log('successfully finished playing'); 
      } else { 
       console.log('playback failed due to audio decoding errors'); 
      } 
     }) 
    } 
+0

事情開始有意義。謝謝蒂莫。 – Jonas

+0

我對你的代碼做的唯一補充是組件類定義之前的'const play = null;'。現在它工作了!謝謝 – Jonas

+0

@Jonas在組件外定義'play'確實不是必需的! – Timo

相關問題