gpt4 book ai didi

javascript - react native : Using props in const

转载 作者:行者123 更新时间:2023-11-29 21:13:24 27 4
gpt4 key购买 nike

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

虽然现在,我正在尝试将 fileName 作为 Prop 从我的类别传递到播放器组件。似乎 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');
}
})
}

关于javascript - react native : Using props in const,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40635783/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com