reactjs - 获取输入文本时,为什么我的 evt.target.value 总是未定义?
问题描述
我正在尝试获取用户输入,保存到变量,然后发送到商店。但无论我尝试什么,我总是得到“未定义”,这是为什么呢?
我觉得我什么都试过了。我最初认为我的范围是错误的。然后我以为它只是无法setState/getState,但它正在设置状态,就像未定义一样。
import React from 'react';
import { View } from 'react-native';
import { Button, Input } from 'react-native-elements';
export default class HomeScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
inputValue: ''
};
}
//update input value
updateInputValue(evt) {
console.log(evt)
console.log(evt.target.value)
let saveInputValue = evt.target.value
this.setState({
inputValue: saveInputValue
});
console.log(this.state)
}
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Input
placeholder='User Input'
containerStyle={{width:'50%'}}
value={this.state.inputValue}
onChange={evt => this.updateInputValue(evt)}
/>
<View style={{flex:0.03}}/>
<Button title="Go to Second Screen"
//onPress={() => {this.handleClick()}}
buttonStyle={{ backgroundColor: '#C7D8C6' }}
/>
</View>
);
}
}
在 updateInputValue(evt) 函数中:
console.log(evt) = SyntheticEvent {dispatchConfig: {phasedRegistrationNames: {captured: "onChangeCapture", bubbled: "onChange"}}, _targetInst: FiberNode, _dispatchListeners: function, _dispatchInstances: FiberNode, nativeEvent: {target: 3, text: "D", eventCount: 1}, …}
最初console.log(evt.target.value) = {inputValue: ''}
(如预期)
但是onChangeconsole.log(evt.target.valur) = {inputValue: undefined}
以后访问此帖子的任何人的答案
下面的几个人建议了这种最简单的方法(谢谢):
如果您只需要文本值本身,请改用 onChangeText 事件 >:
onChangeText={text => this.updateInputValue(text)}
react-native-elements 输入只是 React Native TextInput 的包装器,并继承了它的所有道具,如您在文档中所见。
解决方案
您可以执行以下操作来完成这项工作。
1- 使用 onChange 中的箭头函数尝试 setState。
onChange={event => this.setState({inputValue: event.target.value})}
2-尝试使您的 updateInputValue 方法成为箭头函数,因为在 javascript 上下文中,它会根据您调用函数的方式而变化。
updateInputValue = (evt) => {
console.log(evt)
console.log(evt.target.value)
let saveInputValue = evt.target.value
this.setState({
inputValue: saveInputValue
});
console.log(this.state)
}
推荐阅读
- rx-java2 - RxJava - flatMap 在同一个线程上
- php - 升级到 PHP 7.1
- php - 使用 Ajax 和 Codeigniter 将图像上传到数据库
- c++ - 在 dynamic_pointer_cast 之后调用派生类的构造函数
- dart - 日期时间时区反序列化
- android-studio - 在 Android Studio 中是否有在一个操作中复制和删除行的快捷方式?
- sql - 如何在sql中设置条件?
- azure - 在 RedHat (Azure) 上安装 Docker 后登录控制台
- python - 如何在 Flipkart 评论中获取更多评论数据
- spring-boot - 如何使用 th:each 在 thymeleaf 中加载 Spring message.properties