gpt4 book ai didi

javascript - Undefined 不是一个对象(评估 'this. state.input' )

转载 作者:行者123 更新时间:2023-11-28 05:35:34 25 4
gpt4 key购买 nike

我正在尝试从 json 文件读取 key 并在文本字段中显示其值。用户将在 TextInput 字段中输入键值。以下是我使用的代码。输入文本并按下提交按钮后,它会抛出“未定义不是对象(评估'this.state.input')”错误。我认为将值绑定(bind)/传递给 showMeaning() 函数存在一些问题。请帮忙。

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

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

showMeaning() {
var meaning = this.state.input in english_german ? english_german[this.state.input] : "Not Found";
this.setState({
output: meaning
});
}

render() {
return (
<View style={styles.parent}>
<Text>
Type something in English:
</Text>
<TextInput value={this.state.input}
onChangeText={(input) => this.setState({ input }) }
onSubmitEditing = {this.showMeaning}
/>
<Text style={styles.germanLabel}>
Its German equivalent is:
</Text>
<Text style={styles.germanWord}>
{this.state.output}
</Text>
</View>
);
}
};

var styles = StyleSheet.create({
parent: {
padding: 16
},
germanLabel: {
marginTop: 20,
fontWeight: 'bold'
},
germanWord: {
marginTop: 15,
fontSize: 30,
fontStyle: 'italic'
}
});

AppRegistry.registerComponent('Dictionary', function () {
return Dictionary;
})

最佳答案

当您调用 showMeaning 时,它未绑定(bind)到正确的上下文 (this)。你应该bind它或使用具有词法 this 的箭头函数,例如:

onSubmitEditing = {() => this.showMeaning()}

关于javascript - Undefined 不是一个对象(评估 'this. state.input' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39394128/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com