繁体   English   中英

React Native:在 const 中使用 props

[英]React Native: Using props in const

我是本机反应/反应的新手,并试图构建一个播放本地 MP3 的简单应用程序。 我正在使用 react-native-sound 模块,它似乎工作得很好。

虽然现在,我试图将fileName作为道具从我的类别传递给播放器组件。 似乎 react-native-sound 需要我预加载一个声音文件。 因此,现在我收到以下错误:

“未处理的 JS 异常:无法读取未定义的属性‘fileName’”。

...    
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');
        }
      })
    }
...

你对我有什么建议吗?

您无法以尝试使用它的方式从类外部访问类实例的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');
            }
        })
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM