首页 > 解决方案 > 从不使用状态的参考中获取文本值

问题描述

我正在尝试使用参考从 TextInput 获取一个值,但它总是打印未定义。我不知道为什么会这样。

 <TextInput 
   ref={value =>this._passwordRef = value }
   style={styles.inputTextStyle} placeholder='Enter password here'>  
    </TextInput>


 <TouchableOpacity onPress={(view)=>{this.onSubmit()}} style={{height:50,borderColor:'#000',borderWidth:2,marginLeft:20,marginRight:20}}>
              <Text style={styles.btnTextStyle}>Submit</Text>
              </TouchableOpacity>

  onSubmit(){
      console.log(this._passwordRef._lastNativeText);
  }

当前版本的反应是。

“反应”:“16.13.1”,“反应原生”:“0.63.3”

标签: react-native

解决方案


根据 ReactNative 文档,TextInput 似乎没有参考道具。

onChangeText您需要使用and来处理更改和检查输入的值value。检查下面的代码以获得更好的理解

import React, { Component } from 'react';
import { TextInput } from 'react-native';

const TextInputtt = () => {
  const [value, onChangeText] = React.useState('Useless Placeholder');

  return (
    <TextInput
      style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
      onChangeText={text => onChangeText(text)}
      value={value}
    />
  );
}

export default TextInputtt;

推荐阅读