Cannot access this.props from string to function

fli*_*lix 5 javascript reactjs react-native

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()}
  )
}
Run Code Online (Sandbox Code Playgroud)

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

谁能帮我为什么会这样?

Yoc*_*oka 2

尝试将其绑定到您的函数:

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()}
  )
}
Run Code Online (Sandbox Code Playgroud)

这不是一个好的做法 - 每次渲染绑定都会创建一个新函数 -new Function我建议您将此功能移动到带有参数的普通函数中,而不是使用。