this tutorialに従って、英語の単語をドイツ語に翻訳する単語辞書を作成しようとしています。それはjsonファイルを利用しています。これは英語の単語とそれに対応するドイツの単語をキーにしたものです。React Native Undefinedはオブジェクトではありません(this.state.inputを評価する)
チュートリアルが必要と声明
var english_german = require('./english_german.json');
を使用しますが、私ではなく、import文を使用して、代替があるかどうかを知りたいことをやります。私が直面している主な問題は、TextInputに単語を入力してEnterキーを押すと「定義されていないオブジェクト(評価された '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にする方が良いかどうかによって異なります。 –