简体   繁体   中英

Cannot access this.props from string to function

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?

Do you want to try after changing the code as follows?

  constructor(props) {
    super(props);
    this.state = {
        stringToFn="navigate(\'otherscreen\')",
        stringToFn2="alert(\'otherscreen\')"
    };
...
render() {
const { navigate } = this.props.navigation;
...
 let nyobaFunc = new Function('navigate',`return  + ${this.state.stringToFn}`)

   <TouchableOpacity onPress={() => nyobaFunc(navigate)} style={styles.flatListButton}>

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.

Looks like your navigation prop is undefined. Add a null check before invoking.

this.props.navigation && this.props.navigation.navigate(\'otherscreen\')

From your comment i want to create a dynamic function, so the function getting from API, i need to convert the string of function into the function itself I think you want a solution where you are mapping a string to possible functions.

import React from 'react';
import { StyleSheet, Text, TouchableOpacity, View } from 'react-native';

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center'
  }
});

class App extends React.Component {
  handlePress = () => {
    const taskName = 'navigate'; // get the name of the task from api

    // taskName to task mapping
    switch (taskName) {
      case 'navigate':
        this.props.navigation.navigate('otherscreen');
        break;
      case 'alert':
        alert('otherscreen');
        break;
    }
  };

  render() {
    return (
      <View style={styles.container}>
        <TouchableOpacity onPress={this.handlePress}>
          <Text>Do API Task</Text>
        </TouchableOpacity>
      </View>
    );
  }
}

export default App;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM