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');
}
})
}
...
你有任何指针,我如何去了解呢?
答
您无法以您尝试使用它的方式从课程外部访问班级实例的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');
}
})
}
在组件类定义之外没有'this.props'。 – pawel
在第三行中,您使用this.props.filename约定'Sound',但'this'指向窗口并且没有道具 – MichaelB
词法范围;} – jdmdevdotnet