I want to know why i can use this.props
directly but i can't use this.props
from string into function
.
the error is:
undefined is not an object (evaluating 'this.props.navigation')
here a sample code i've tried:
state={
stringToFn="this.props.navigation.navigate(\'otherscreen\')",
stringToFn2="alert(\'otherscreen\')"
}
renderThis(){
let nyobaFunc = new Function("return " + "()=>{"+this.state.stringToFn+"}")();
return(
<TouchableOpacity onPress={nyobaFunc} style={styles.flatListButton}>
<CustomText style={styles.flatListSubTitle}>{'HitMe!'}</CustomText>
</TouchableOpacity>
)
}
render(){
return(
{this.renderThis()}
)
}
but if i put stringToFn
value into onPress
directly or if i change this.state.stringToFn
to this.state.stringToFn2
in nyobaFunc
, it's work like a charm
can anyone help me why this can be happened?
Try to bind this to your function:
state={
stringToFn="this.props.navigation.navigate(\'otherscreen\')",
stringToFn2="alert(\'otherscreen\')"
}
renderThis(){
let nyobaFunc = new Function(`return ${this.state.stringToFn}`);
return(
<TouchableOpacity onPress={nyobaFunc.bind(this)} style={styles.flatListButton}>
<CustomText style={styles.flatListSubTitle}>{'HitMe!'}</CustomText>
</TouchableOpacity>
)
}
render(){
return(
{this.renderThis()}
)
}
This is not a good practice - each renders the bind will create a new function - instead of using new Function
I recommended that you move this functionallity into normal function with parameter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With