繁体   English   中英

如何在不使用状态的情况下在 React Native 中获取 TextInput 的值

[英]How to get the value of TextInput in React Native without using state

我知道我可以使用this.state做到这this.state但我想让我的代码统一。 我有通过 API 连接的网络应用程序和移动应用程序。

这是我的 ReactJS Web 应用程序的样子(这个有效)

import React from 'react'

export default class SignIn extends React.Component {
  signIn = () => {
    var username = this.refs.username.value;
    var password = this.refs.password.value;

    console.log(username); //works
    console.log(password); //works
  }
  render () {
    return (
      <div>
        <input ref='username' placeholder='Username' />
        <input ref='password' type='password' placeholder='Password' />
        <button onClick={this.signIn.bind(this)}>Submit</button>
      </div>
    );
  }
}

上面的代码没有使用任何状态来获取文本框的值,我想在 React Native 中实现同样的事情。

在我的移动应用程序中,我有以下代码(这不起作用)

import React from 'react';
import {Alert, TextInput, View, Button} from 'react-native';

export default class App extends React.Component {
  signIn = () => {
    var username = this.refs.username.value;
    var password = this.refs.password.value;

    Alert.alert(username); //doesn't work
    Alert.alert(password); //doesn't work
  }
  render() {
    return (
      <View style={{marginTop: 60}}>
        <TextInput ref='username' placeholder='Username' autoCapitalize='none' />
        <TextInput ref='password' placeholder='Password' autoCapitalize='none' secureTextEntry={true} />
        <Button title='Submit' onPress={this.signIn.bind(this)} />
      </View>
    );
  }
}

我希望代码尽可能统一,但相同的逻辑在 React Native 中不起作用。 是否可以在不使用状态的情况下执行此操作?

使用this.refs.username._lastNativeText获取username this.refs.username._lastNativeText的内部文本值。

然而,根据官方 RN 指南,这不是最好的方法。 有关更多详细信息,请参阅此 SO 答案

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM