我试图建立一个单词字典,通过遵循this tutorial将英语单词翻译成德语单词。它使用了一个json文件,我相信它包含带有英文单词的键和相应的德语单词作为值。React Native Undefined不是一个对象(正在评估'this.state.input')
本教程做的,通过使用需要声明
var english_german = require('./english_german.json');
,但我想知道是否有使用import语句,而不是替代。我面临的主要问题是,当我在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);
您也可以使用箭头语法自动绑定:'showMeaning =()=> {//此处的方法}' –
@AndrewBreen没有绑定,'this'是指什么? – Benjamin
这取决于它,它可以引用其他组件,但要确保它更好console.log它。 –