简体   繁体   English

无法从字符串到函数访问this.props

[英]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 . 我想知道为什么我可以直接使用this.props但我不能使用this.props从string到function

the error is: 错误是:

undefined is not an object (evaluating 'this.props.navigation') undefined不是一个对象(评估'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 但是如果我将stringToFn值直接放入onPress ,或者如果我将this.state.stringToFn更改为this.state.stringToFn2中的nyobaFunc ,它的工作就像一个魅力

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. 这不是一个好习惯 - 每次渲染绑定都会创建一个新函数 - 而不是使用new Function我建议您将此函数全部移动到带参数的常规函数​​中。

Looks like your navigation prop is undefined. 看起来您的navigation道具未定义。 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. 从你的评论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我认为你想要一个解决方案,你将字符串映射到可能的函数。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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