在 React Native 中提供了一個文本輸入組件TextInput
。此組件主要是監(jiān)聽鍵盤輸入事件,并把對應(yīng)的輸入值顯示在組件中,此組件還提供了很多功能配置參數(shù),例如自動更正、自動大寫、占位符文本和不同的鍵盤類型(例如數(shù)字鍵盤)。
我們首先來編寫一個簡單的實(shí)例,使用onChangeText
事件監(jiān)聽用戶的輸入:
export default function InputText() {
const [name, setName] = useState<string>("");
const [age, setAge] = useState<string>("");
return (
<View style={styles.container}>
<Text style={styles.mainTitle}>InputText 組件實(shí)例</Text>
<View style={styles.formItem}>
<Text style={styles.labelTitle}>姓名:</Text>
<TextInput
style={styles.formInput}
placeholder="請輸入姓名"
value={name}
onChangeText={(value) => setName(value)}
></TextInput>
</View>
<View style={styles.formItem}>
<Text style={styles.labelTitle}>年齡:</Text>
<TextInput
style={styles.formInput}
keyboardType="numeric"
placeholder="請輸入年齡"
value={age}
onChangeText={(value) => setAge(value)}
></TextInput>
</View>
<View style={styles.infoContainer}>
<Text>姓名:{name}</Text>
<Text>年齡:{age}</Text>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
margin: 8,
},
mainTitle: {
fontSize: 22,
fontWeight: "bold",
padding: 10,
borderBottomWidth: 1,
borderColor: "#e3e3e3",
},
input: {
borderWidth: 1,
borderRadius: 4,
borderColor: "#e3e3e3",
marginVertical: 8,
padding: 8,
},
formItem: {
flexDirection: "row",
justifyContent: "flex-start",
alignItems: "center",
rowGap: 8,
columnGap: 8,
marginVertical: 12,
},
labelTitle: {
fontSize: 16,
},
formInput: {
borderWidth: 1,
borderRadius: 6,
paddingHorizontal: 10,
paddingVertical: 6,
flex: 1,
},
infoContainer: {
flexDirection: "row",
marginVertical: 8,
justifyContent: "center",
alignItems: "center",
rowGap: 8,
columnGap: 8,
},
});
TextInput
組件除了可以監(jiān)聽onChangeText
事件外,還可以監(jiān)聽.focus()
和.blur()
事件。并且此組件還可以通過設(shè)置multiline
屬性來允許用戶輸入多行文本數(shù)據(jù),例如我們可以允許用戶最多輸入 4 行文本,字?jǐn)?shù)最大 100 個字符:
<View style={styles.formItem}>
<Text style={styles.labelTitle}>備注:</Text>
<TextInput
style={styles.formInput}
multiline
numberOfLines={4}
maxLength={100}
placeholder="請輸入備注"
value={summary}
></TextInput>
</View>
默認(rèn)情況下,TextInput 在其視圖底部有一個邊框。該邊框的內(nèi)邊距由系統(tǒng)提供的背景圖像設(shè)置,并且無法更改。避免這種情況的解決方案是要么不顯式設(shè)置高度,在這種情況下系統(tǒng)將負(fù)責(zé)在正確的位置顯示邊框,要么通過將 underlineColorAndroid 設(shè)置為透明來不顯示邊框。underlineColorAndroid
此屬性只是針對于安卓設(shè)備而言。文章來源:http://www.zghlxwxcb.cn/news/detail-662603.html
請注意,在 Android 上,在輸入中執(zhí)行文本選擇可以將應(yīng)用程序的活動 windowSoftInputMode 參數(shù)更改為 adjustmentResize。當(dāng)鍵盤處于活動狀態(tài)時,這可能會導(dǎo)致具有“絕對”位置的組件出現(xiàn)問題。要避免此行為,請?jiān)?AndroidManifest.xml 中指定 windowSoftInputMode 或使用本機(jī)代碼以編程方式控制此參數(shù)。文章來源地址http://www.zghlxwxcb.cn/news/detail-662603.html
到了這里,關(guān)于React Native 文本輸入基礎(chǔ)知識的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!