React Native:在const中使用props

时间:2016-11-16 15:20:08

标签: javascript reactjs react-native react-native-router-flux

我是新手做出反应/反应原生并尝试构建一个播放本地MP3的简单应用。我使用的是反应原生声音模块,它似乎运行得很好。

虽然现在,我试图将ControlValueAccessor作为道具从我的类别传递到播放器组件。 似乎反应本机声音需要我预加载声音文件。因此,现在我收到以下错误:

  

"未处理的JS异常:无法读取属性' fileName'的   未定义"

fileName

你有什么指示我如何解决这个问题吗?

1 个答案:

答案 0 :(得分: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');
            }
        })
    }
相关问题