我有一個輸入將其值傳遞給useState其父級上的 a 。該值被傳遞給其他組件(自定義按鈕)。如果出現錯誤,則輸入資料將在另一個 useState 中得到驗證并回傳到父級(“e” = 電子郵件錯誤,“p” = 密碼錯誤,“ep” = 電子郵件和密碼錯誤)
然后邊框輸入的顏色根據該回應進行相應設定,如果有錯誤則變為紅色,否則變為白色。
但它只在我第二次按下按鈕時起作用(一切都應該開始)
幫助!??
const LoginScreen = () => {
const [email, setemail] = useState('');
const [password, setpassword] = useState('');
const [error, seterror] = useState('');
return (
<View style={styles.container}>
<Input
placeholder={"Correo :"}
setInputValue={value => setemail(value)}
color={
error.includes("e") ? '#FA8072' : 'white'
}
/>
<Input
placeholder={"Contrase?a :"}
setInputValue={value => setpassword(value)}
color={
error.includes("p") ? '#FA8072' : 'white'
}
/>
<LoginButton data={{email: email, password: password}} setValue={value => {seterror(value)}}/>
</View>
)
}
==========================================
輸入組件
const Input = (props) => {
return (
<View style={styles.container}>
<Text style={styles.placeholder}>{props.placeholder}</Text>
<TextInput
style={[styles.input, {borderColor: props.color}]}
onChangeText={(value) => props.setInputValue(value)}
/>
</View>
)
}
==========================================
按鈕組件
const LoginButton = (props) => {
const [inputError, setinputError] = useState('')
let validateData = () => {
if(!props.data.email && !props.data.password){
setinputError('ep')
}
else if(!props.data.email){
setinputError('e')
}
else if(!props.data.password){
setinputError('p')
}
else {
setinputError('')
}
}
return (
<TouchableOpacity style={styles.mainButton} onPress={() => {validateData(); props.setValue(inputError)}}>
<Text style={styles.mainButtonText}>Iniciar sesión</Text>
</TouchableOpacity>
)
}
uj5u.com熱心網友回復:
因為你試圖改變狀態兩次。實際上,您不需要使用 state 在 LoginButton 組件中傳遞值。改為嘗試直接呼叫。
const LoginButton = (props) => {
let validateData = () => {
if(!props.data.email && !props.data.password){
props.setValue("ep");
}
else if(!props.data.email){
props.setValue('e');
}
else if(!props.data.password){
props.setValue('p');
}
else {
props.setValue('');
}
}
return (
<TouchableOpacity style={styles.mainButton} onPress={() => validateData()}>
<Text style={styles.mainButtonText}>Iniciar sesión</Text>
</TouchableOpacity>
)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/353519.html
標籤:javascript 反应原生 使用状态 反应功能组件 可触摸不透明度
上一篇:Python制作大型NxN矩陣
下一篇:反應原生視圖條件渲染
