componentDidMount

时间:2019-11-15 20:52:39

标签: react-native react-native-sound

我想在componentDidMount中播放音乐,但是我的代码不起作用

import React,{Component} from 'react'
import Nav from './Nav'
import Sound from 'react-native-sound'
const play = new Sound('music.mp3')

class App extends Component {
  componentDidMount(){
          play.play()
  }
  render(){ 
    return(
      <Nav />
    )
  }}
export default App

1 个答案:

答案 0 :(得分:1)

根据文档,您应该在构造函数中使用回调:

import React,{Component} from 'react'
import Nav from './Nav'
import Sound from 'react-native-sound'

class App extends Component {
  componentDidMount(){
    const play = new Sound('music.mp3', (error, play) => {
      if (error) return
      else play.play(() => {
        play.release() // release when done to release resources
      })
    })
  }
  render(){ 
    return(
      <Nav />
    )
  }}
export default App