Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot access this.props from string to function

Tags:

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?

like image 823
flix Avatar asked Aug 02 '19 06:08

flix


1 Answers

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.

like image 185
Yochai Akoka Avatar answered Oct 03 '22 07:10

Yochai Akoka