[英]Updating Parent component state from Child component TextInput in React Native
我有一個調查問題列表,作為供用戶填寫的組件,我正在嘗試檢查每個問題並在填寫子組件輸入字段時更新父組件狀態,但是在第一個組件上我一直在接收文本來自未定義的 TextInput。
這是我的父組件“SurveyScreen”:
export default function SurveyScreen({navigation, route}) {
const [childNameValue, setChildNameValue] = useState('');
function handleChange(newValue) {
setChildNameValue(newValue);
console.log(childNameValue);
}
return (
<ScrollView style={styles.cardContainer}>
<View>
<Text style={styles.title}>Please fill out all questions below</Text>
</View>
<View>
<BasicTextInput
title="Child's full name"
value={childNameValue}
onChange={handleChange}
/>
);
}
我的子組件“BasicTextInput”:
import React, {useState} from 'react';
import {
View,
Text,
StyleSheet,
Pressable,
Platform,
TextInput,
} from 'react-native';
import CheckBox from '@react-native-community/checkbox';
export default function BasicTextInput({title, onChange}, props) {
const [text, onChangeText] = useState('');
function handleChange(e) {
onChange(e.target.value);
}
return (
<View>
<View>
<Text>title</Text>
</View>
<View>
<TextInput
style={styles.input}
onChange={handleChange}
value={props.childNameValue}
/>
<View />
</View>
</View>
);
}
我刪除了一些樣式和導入以保持簡單,在 BasicTextInput 上輸入文本時,我在父級中獲得的控制台日志是“未定義”
我想我錯過了一些簡單的東西,但任何幫助將不勝感激! 我有很多這樣的事情要做,所以想讓這個初始組件正確。
提前致謝。
問題在下線
export default function BasicTextInput({title, onChange}, props) {
這里 BasicTextInput 是組件,它接收單個參數作為道具,所以如果你想重組它,它將是
export default function BasicTextInput({title, onChange}) {
最后,我能夠通過傳入一個 onChangeValue 作為道具來實現這一點,該道具采用 newValue 並將狀態設置為該 newValue。
以下是兩個更新的文件作為示例:
export default function SurveyScreen({navigation, route}) {
const [childNameValue, setChildNameValue] = useState('');
return (
<ScrollView style={styles.cardContainer}>
<View>
<Text style={styles.title}>Please fill out all questions below</Text>
</View>
<View>
<BasicTextInput
title="Child's full name"
value={childNameValue}
onChangeValue={newValue => setChildNameValue(newValue)}
/>
);
}
還有我的子組件文件:
export default function BasicTextInput({title, onChangeValue}) {
return (
<View style={styles.container}>
<View style={styles.containerHeader}>
<Text style={styles.questionTitle}>{title}</Text>
</View>
<View style={styles.answerContainer}>
<TextInput style={styles.input} onChangeText={onChangeValue} />
<View />
</View>
</View>
);
}
我希望這對你們中的一些人有幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.