React Native Undefined 不是对象(评估 'this.state.input')

React Native Undefined is not an Object (evaluating 'this.state.input')

我正在尝试构建一个单词词典,按照 this tutorial 将英语单词翻译成德语单词。它利用了一个 json 文件,我相信该文件包含以英语单词及其相应的德语单词作为值的键。

  1. 本教程通过使用 require 语句来做到这一点 var english_german = require('./english_german.json'); 但我想知道是否有使用 import 语句的替代方法。

  2. 不过,我面临的主要问题是,当我在 TextInput 中输入一个词并按回车键时,出现 "Undefined is not an Object (evaluating 'this.state.input')" 错误。

我的源码如下:

import React, { Component } from 'react';
import {
  AppRegistry,
  Image,
  StyleSheet,
  Text,
  TextInput,
  View
} from 'react-native';

var english_german = require('./english_german.json');

class Dictionary extends Component {
  constructor(props) {
    super(props);
    this.state = {
      input: '',
      output: ''
    }
    

  }
  
  showMeaning() {
    // Use the ternary operator to check if the word
    // exists in the dictionary.
    var meaning = this.state.input in english_german ?
                    english_german[this.state.input] :
                    "Not Found";
    // Update the state
    this.setState({output: meaning});
  }
  
 render() {
  var layout = 
   <View style = { styles.parent }>
    <Text>
     Type something in English:
    </Text>
        <TextInput
          onChangeText={(e) => this.setState({input: e})}
          text = { this.state.input }
          onSubmitEditing = { this.showMeaning }
        />
    <Text style = { styles.germanLabel }>
     It's German equivalent is:
    </Text>
    <Text style = { styles.germanWord }>
          { this.state.output }
    </Text>
   </View>
  ;
  return layout;
 }
}

const styles = StyleSheet.create({
 // For the container View
 parent: {
  padding: 16
 },
 // For the Text Label
 germanLabel: {
  marginTop: 20,
  fontWeight: 'bold'
 },
 // For the Text meaning
 germanWord: {
  marginTop: 15,
  fontSize: 30,
  fontStyle: 'italic'
 }
});

AppRegistry.registerComponent('Dictionary', () => Dictionary);

这是因为您指的是 showMeaning 内的 this。像这样 this.showMeaning = this.showMeaning.bind(this).

将该函数绑定到 constructor 内的右 this

我强烈建议您阅读 React 基础知识。例如,这里是您的问题的文档:https://facebook.github.io/react/docs/handling-events.html

这是一个绑定问题,请在您的构造函数中添加:

this.showMeaning = this.showMeaning.bind(this);

这将确保您的 showMeaning 方法中的 this 对象引用您的 Dictionary 组件。或者,您可以在 showMeaning 方法中使用箭头函数,如下所示:

showMeaning = () => { /* rest of code */ }

箭头函数保留了this的上下文。所以不需要使用 bind