首页 > 解决方案 > 获取输入文本时,为什么我的 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 的包装器,并继承了它的所有道具,如您在文档中所见。

标签: reactjsreact-nativeecmascript-6

解决方案


您可以执行以下操作来完成这项工作。

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)

  }

推荐阅读