如何在React-Native中读取已填充的TextInput?

问题描述 投票:1回答:2

我有一个TextInput:通常我可以在有变化时读取TextInput,问题是密码的TextInput是用默认密码填充的。因此用户可能不需要编辑(更改)它 - 因此不会触发onChangeText方法。

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

export default class App extends Component {
  constructor(props){
    super(props);
    this.state = { 
      username: '', 
      password: 12345 
    }
  }

  onChangeText = (key, val) => {
    this.setState({ [key]: val})
  }

  render() { 
    return (
      <View style={styles.container}>
          <Text>Login Form</Text>
          <TextInput
            placeholder='Username'
            onChangeText={val => this.onChangeText('username', val)}
            style={styles.input}
            value={this.state.username}
          />
          <TextInput
            placeholder='Password'
            onChangeText={val => this.onChangeText('password', val)}
            style={styles.input}
            value={this.state.password}
            secureTextEntry={true}
          />      
      </View>
    );
  }
}

现在,我的问题是如何阅读未被更改的文本输入?

javascript react-native expo
2个回答
0
投票

将TextInput value prop更改为defaultValue。我认为这可行。 TextInput value prop不允许修改现有值。

<TextInput
            placeholder='Password'
            onChangeText={val => this.onChangeText('password', val)}
            style={styles.input}
            defaultValue={this.state.password}
            secureTextEntry={true}
          /> 

0
投票

有一种方法可以通过refs直接从组件中获取TextInput值。

如果输入从value prop接收文本,您可以使用_lastNativeText方法,如下例所示。

export default class App extends Component {

  state = {
    text: 'Hello!'
  }

  constructor(props) {
    super(props);
    this.inputRef = React.createRef();
  }

  componentDidMount() {
    this.printTextInputValue();
  }

  printTextInputValue = () => {
    const input = this.inputRef.current;
    console.log(input._lastNativeText);
  }

  render() {
    return (
      <View style={styles.container}>
        <TextInput value={this.state.text} ref={this.inputRef} />
        <Button onPress={this.printTextInputValue} title="Get input value"  />
      </View>
    );
  }
}

如果TextInput使用defaultValue prop使用_getText方法来读取初始值。

export default class App extends Component {

  constructor(props) {
    super(props);
    this.inputRef = React.createRef();
  }

  componentDidMount() {
    this.printDefaultInputValue();
  }

  printDefaultInputValue = () => {
    const input = this.inputRef.current;
    console.log(input._getText());
  }

  printTextInputValue = () => {
    const input = this.inputRef.current;
    console.log(input._lastNativeText);
  }

  render() {
    return (
      <View style={styles.container}>
        <TextInput defaultValue="Hello Default!" ref={this.inputRef} />
        <Button onPress={this.printTextInputValue} title="Get input value"  />
      </View>
    );
  }
}

但请注意,这些方法尚未正式记录,可能会在React Native的未来版本中删除,因此请自行决定使用它们。

© www.soinside.com 2019 - 2024. All rights reserved.