React Native:undefined不是对象

时间:2017-11-12 22:50:20

标签: reactjs react-native expo

我目前正在学习React Native。

我只是构建了一个非常简单的应用来测试Button组件。

单击按钮组件时,将按预期打印控制台日志。 但是在打印出控制台日志后,它会弹出以下错误。

+----+------+--------+--------------------+
| ID | Name |  Job   |       Colors       |
+----+------+--------+--------------------+
|  1 | John | Worker | Blue Yellow Green  |
|  2 | Jane | Worker | Orange             |
+----+------+--------+--------------------+

我不确定是什么问题?

有谁能让我知道我做错了什么?

**undefined is not an object (evaluating '_this2.btnPress().bind')**

1 个答案:

答案 0 :(得分:2)

您正在调用该函数,而不是通过bind传递引用 放松()
而且你不应该用箭头函数bind is already returning a new function instance

来包装它
onPress={this.btnPress.bind(this)} />

顺便说一下,这将返回并在每个渲染上创建一个函数实例,你应该在constructor(只运行一次)中执行一次:

export default class App extends React.Component {
    constructor(props){
        super(props);
        this.btnPress = this.btnPress.bind(this);
    }
     btnPress() {
       console.log("Fn Button pressed");
     }

      render() {
        return (
          <View style={styles.container}>
            <Button title="this is a test"
              onPress={this.btnPress} />
          </View>
        );
      }
    }

或者使用箭头函数,该函数使用this的词汇上下文:

export default class App extends React.Component {

     btnPress = () => {
       console.log("Fn Button pressed");
     }

      render() {
        return (
          <View style={styles.container}>
            <Button title="this is a test"
              onPress={this.btnPress} />
          </View>
        );
      }
    }
相关问题