React Native:使用const中的道具

问题描述:

我是新手,反应/反应本地,并试图构建一个播放本地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

您无法以您尝试使用它的方式从课程外部访问班级实例的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