简体   繁体   中英

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

I have code for a custom TextInput component and I want to use this component for both a username and password value for a login screen, however, I don't know how to retrieve the value of the text input for a specific instance.

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>
  );
}

After Importing I created in my login screen

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

How do I get the value so that I can assign it to a variable for each TextInputCustom instance?

You need to move the value and onChange to the parent level:

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>
  );
}

And then use it like this:

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

This is the practice that is used in general for simple components. You don't need to handle the value in the component level, but in the component that is using your custom component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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