J'essaie de construire un dictionnaire de mots qui traduit des mots anglais en mots allemands en suivant this tutorial. Il utilise un fichier json qui, je crois, contient des clés avec des mots anglais et ses mots allemands correspondants comme valeurs.React Native Undefined n'est pas un objet (évaluation 'this.state.input')
Le tutoriel faire en utilisant l'require
var english_german = require('./english_german.json');
mais je voudrais savoir s'il existe une alternative en utilisant l'instruction d'importation à la place. Le problème principal auquel je suis confronté, cependant, est que j'obtiens une erreur "Undefined n'est pas un objet (en évaluant 'this.state.input')" quand je tape un mot dans le TextInput et que je tape enter .
Mon code source est la suivante:
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);
Vous pouvez également lier automatiquement à l'aide de la syntaxe fléchée: 'showMeaning =() => {// Méthode ici}' –
@AndrewBreen Sans la liaison, à quoi cela fait-il référence? – Benjamin
Cela dépend, il pourrait se référer à d'autres composants, mais pour être sûr qu'il est préférable de consoler.log. –