簡體   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