[英]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.我有自定义 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>
);
}
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?如何获取该值以便可以将其分配给每个 TextInputCustom 实例的变量?
You need to move the value
and onChange
to the parent level:您需要将value
和onChange
移动到父级别:
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.您不需要在组件级别处理值,而是在使用自定义组件的组件中处理值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.