Reputation: 91
I get Cannot read property 'callToPrayer' of undefined
import { adhaan } from './assets/audio.js'
export default class JustPrayClient extends Component {
constructor (props) {
super(props)
// this.props = props
this.playSound.bind(this)
}
playSound () {
// console.log(this.props.test)
this.props.callToPrayer.play() //why is props undefined here?
}
render () {
return (
<View style={styles.container}>
<Text onPress={this.playSound} style={styles.welcome}>
Welcome to React Native! {this.props.test}
</Text>
</View>
)
}
}
const Main = () => <JustPrayClient callToPrayer={adhaan} test='hello' />
Does this have something to do with the this context?
If so, I don't know where/how I should bind this...
Upvotes: 0
Views: 3493
Reputation: 282130
You are not binding playSound
function correctly in the constructor. You need to assign it back to the function like
this.playSound = this.playSound.bind(this)
Try this and it should fix you problem. However if you are using webpack and correctly specifying the presets in the module loaders then, binding with arrow functions also functions correclty
playSound = () = > {
console.log(this.props.callToPrayer);
}
Also check if play()
function is getting available to the playSound function once you console.log()
it and if it is available then you can use it.
Upvotes: 2
Reputation: 15642
you have two choices:
.bind
in constructor
constructor (props) {
super(props);
this.playSound = this.playSound.bind(this);
}
OR
use Arrow Function to define playSound
playSound = () => {
this.props.callToPrayer.play();
}
Upvotes: 1