我有一個調查問題串列,作為供用戶填寫的組件,我正在嘗試檢查每個問題并在填寫子組件輸入欄位時更新父組件狀態,但是在第一個組件上我一直在接收文本來自未定義的 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 上輸入文本時,我在父級中獲得的控制臺日志是“未定義”
我想我錯過了一些簡單的東西,但任何幫助將不勝感激!我有很多這樣的事情要做,所以想讓這個初始組件正確。
提前致謝。
uj5u.com熱心網友回復:
問題在下線
export default function BasicTextInput({title, onChange}, props) {
這里 BasicTextInput 是組件,它接收單個引數作為道具,所以如果你想重組它,它將是
export default function BasicTextInput({title, onChange}) {
uj5u.com熱心網友回復:
最后,我能夠通過傳入一個 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>
);
}
我希望這對你們中的一些人有幫助!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/357531.html
標籤:javascript 反应 反应原生 成分 状态
上一篇:將陣列分成相等的兩半
下一篇:如何訪問打字稿中的組件
