如何获取 <TextInput> 的值在 onPress 处理程序中? [英] How to get the value of a &lt;TextInput&gt; in an onPress handler?

查看:40
本文介绍了如何获取 <TextInput> 的值在 onPress 处理程序中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 并且我通过这样做给它一个 ref 属性:

I've got a <TextInput> and I gave it a ref attribute by doing this:

ref={node => this.usernameInput = node;}

然后,当用户按下 时,我有一个方法来尝试获取 this.usernameInput 的值.this.usernameInput 在我的 onPress 方法中不为空,但我找不到获取它的值的方法!当我这样做时:

Then, I have a method when the user presses a <TouchableInput> that tries to get the value of this.usernameInput. this.usernameInput is not null in my onPress method, but I can't find a way to get the value of it! When I do this:

console.log(this.usernameInput.value);

它记录undefined.如果我设置断点,并检查 this.usernameInput 我可以看到它,但是没有 value 属性或方法,并且我没有看到任何属性或方法可以返回当前值.如何获取 的值?

It logs undefined. If I set a breakpoint, and inspect this.usernameInput I can see it, but there is no value property or method, and I don't see any property or method that could return the current value. How do I get the value of my <TextInput>?

编辑

这是我的组件类:

import {
  View,
  Text,
  TextInput,
  TouchableHighlight
} from 'react-native';
import {Manager as ModalManager} from 'react-native-root-modal';

class AppContainer extends React.Component {
  loginModal;

  constructor(props){
      super(props);
    this._onLoginPress = this._onLoginPress.bind(this);
      this._createLoginModal = this._createLoginModal.bind(this);
  }

  async componentWillMount() {
    this._createLoginModal();
  }

  render() {
      return (
        <View >
          <Text>Hello.</Text>
        </View>
      );
    } 
  }

  _onLoginPress() {
    //this returns 'undefined', although this.usernameInput is not undefined
    console.log(`USERNAMEinputValue: ${this.usernameInput.props.value}`);
  }

  _createLoginModal() {
    this.loginModal = new ModalManager(
        <View >
          <View >

            <Text>Username:</Text>
            <TextInput
              placeholder="Username"
                      ref={node => {
                        this.usernameInput = node;
              }}
            ></TextInput>

            <TouchableHighlight
              onPress={this._onLoginPress}
            >
              <Text>Login</Text>

            </TouchableHighlight>

          </View>
        </View>
    );
  }

}

推荐答案

我发现了一个参数 _lastNativeText ,它在通过 React Native 源代码后保存 TextInput 组件中的文本.您可以使用该参数为您的示例获取如下所示的值.

I found a parameter _lastNativeText which holds the text in TextInput component after going through the react native source code. You may use that param to get the value like below for your example.

this.usernameInput._lastNativeText

但我仍然不建议使用这种方法.最好使用 @jayce444@nifi

But still I would not suggest using this approach. Better to use state based approach suggested by @jayce444 and @nifi

这篇关于如何获取 <TextInput> 的值在 onPress 处理程序中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆