[英]How to get value of child component TextInput of NavigatorIOS in react-native
[英]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 實例的變量?
您需要將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>
);
}
然后像這樣使用它:
<TextInputCustom name="Username" value={username} onChange={onUsernameChange} />
<TextInputCustom name="Password" value={password} onChange={onPasswordChange} />
這是一般用於簡單組件的做法。 您不需要在組件級別處理值,而是在使用自定義組件的組件中處理值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.