2017-06-05 77 views
1

我试图建立一个单词字典,通过遵循this tutorial将英语单词翻译成德语单词。它使用了一个json文件,我相信它包含带有英文单词的键和相应的德语单词作为值。React Native Undefined不是一个对象(正在评估'this.state.input')

  1. 本教程做的,通过使用需要声明var english_german = require('./english_german.json');,但我想知道是否有使用import语句,而不是替代。

  2. 我面临的主要问题是,当我在TextInput中输入一个单词并敲入回车时,出现“未定义不是对象(评估'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}); 
 
    } 
 
    
 
\t render() { 
 
\t \t var layout = 
 
\t \t \t <View style = { styles.parent }> 
 
\t \t \t \t <Text> 
 
\t \t \t \t \t Type something in English: 
 
\t \t \t \t </Text> 
 
     <TextInput 
 
      onChangeText={(e) => this.setState({input: e})} 
 
      text = { this.state.input } 
 
      onSubmitEditing = { this.showMeaning } 
 
     /> 
 
\t \t \t \t <Text style = { styles.germanLabel }> 
 
\t \t \t \t \t It's German equivalent is: 
 
\t \t \t \t </Text> 
 
\t \t \t \t <Text style = { styles.germanWord }> 
 
      { this.state.output } 
 
\t \t \t \t </Text> 
 
\t \t \t </View> 
 
\t \t ; 
 
\t \t return layout; 
 
\t } 
 
} 
 

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

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

回答

4

这是有约束力的问题,添加该在构造函数:

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

这将确保在您的showMeaning方法this对象是指你的Dictionary组件。另外,您也可以使用箭头功能在您showMeaning方法,像这样:

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

箭头功能保留的this上下文。因此不需要使用bind

+1

您也可以使用箭头语法自动绑定:'showMeaning =()=> {//此处的方法}' –

+0

@AndrewBreen没有绑定,'this'是指什么? – Benjamin

+0

这取决于它,它可以引用其他组件,但要确保它更好console.log它。 –

1

这是因为你是指thisshowMeaning内。将此功能绑定到this里面constructor像这样this.showMeaning = this.showMeaning.bind(this)

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

相关问题