2

나는 네이티브 반응을 보이고 로컬 MP3를 재생하는 간단한 앱을 만들려고 노력합니다. 정말 잘 작동하는 반응 - 네이티브 - 사운드 모듈을 사용하고 있습니다.React Native : const에 소품 사용

지금은 fileName을 내 카테고리의 소품으로 플레이어 구성 요소에 전달하려고합니다. 반응하는 네이티브 사운드가 나에게 사운드 파일을 미리로드해야하는 것처럼 보입니다.

"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을 사용하여 '소리'를 계약하지만 'this'는 창을 참조하고 소품이 없습니다 – MichaelB

+1

어휘 범위 지정 : – jdmdevdotnet

답변

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

의미가 있습니다. 티모 감사합니다. – Jonas

+0

당신이 제안한 코드에 추가 한 것은 단지 컴포넌트 클래스 정의 앞에'const play = null;'뿐입니다. 이제 작동합니다! 감사합니다 – Jonas

+0

@Jonas 구성 요소 외부의'play'를 정의하는 것이 꼭 필요한 것은 아닙니다! – Timo

관련 문제