繁体   English   中英

React:如何获取自定义 TextInput 组件的值?

[英]React: How Do I get the value of a custom TextInput Component?

我有自定义 TextInput 组件的代码,我想将此组件用于登录屏幕的用户名和密码值,但是,我不知道如何检索特定实例的文本输入值。

import React from 'react';
import { TextInput, StyleSheet, View, ImagePropTypes } from 'react-native';

const TextInputCustom = (props) => {
  const [value, onChangeText] = React.useState();

  return (
    <View style={styles.container}>
    <TextInput
      placeholder={props.name}
      style={styles.textInput}
      onChangeText={text => onChangeText(text)}
      value={value}
    />
    </View>
  );
}

导入后我在登录屏幕中创建

<TextInputCustom name="Username"/>
<TextInputCustom name="Password"/>

如何获取该值以便可以将其分配给每个 TextInputCustom 实例的变量?

您需要将valueonChange移动到父级别:

import { TextInput, StyleSheet, View, ImagePropTypes } from 'react-native';

const TextInputCustom = (props) => {
  const {value, onChange} = props;

  return (
    <View style={styles.container}>
    <TextInput
      placeholder={props.name}
      style={styles.textInput}
      onChangeText={text => onChange(text)}
      value={value}
    />
    </View>
  );
}

然后像这样使用它:

<TextInputCustom name="Username" value={username} onChange={onUsernameChange} />
<TextInputCustom name="Password" value={password} onChange={onPasswordChange} />

这是一般用于简单组件的做法。 您不需要在组件级别处理值,而是在使用自定义组件的组件中处理值。

暂无
暂无

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

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