我在 React Native 中有一個 signUp 組件(沒有 expo),它可能有多個電子郵件輸入,每個組件后面都有一個 Switch 組件,指示這是否是主要電子郵件。我正在使用 react useState 來管理字段列表的行為。但是當我按下開關來切換主屬性的值時,Switch卡住了,直到我執行下一個操作才移動(在此示例中,我創建了一個按鈕,在數組上插入一個新項,并制作了另一個虛擬工作開關)。但是如果我打印該值,它將按預期正常切換,但組件本身不會立即響應。這是我到目前為止的代碼: import React, {useState} from 'react';import {TextInput, View, Text, Switch, Button} from 'react-native';export default function Signup() { const [isEnabled, setIsEnabled] = useState(false); const [emails, setEmails] = useState([ { email: '', main: true, }, ]); const toggleSwitch = () => setIsEnabled(previousState => !previousState); const setMainEmail = (value, emailIndex) => { const array = emails; console.log(array); array[emailIndex].main = value; console.log(array); setEmails(array); }; const addNewEmail = () => { setEmails([ ...emails, { email: '', principal: false, }, ]); }; return ( <> <View> <Text>Dummy Switch That Works</Text> <Switch trackColor={{false: '#767577', true: '#767577'}} thumbColor={isEnabled ? '#FD7E77' : '#f4f3f4'} ios_backgroundColor="#3e3e3e" onValueChange={toggleSwitch} value={isEnabled} /> </View> <View> {emails.map((email, emailIndex) => ( <View key={emailIndex}> <TextInput placeholder="Email" autoCapitalize="none" keyboardType="email-address" /> <View> <Switch value={email.main} trackColor={{false: '#767577', true: '#767577'}} thumbColor={email.main ? '#FD7E77' : '#f4f3f4'} ios_backgroundColor="#3e3e3e" onValueChange={event => setMainEmail(event, emailIndex)} /> <Text color="#fff">Main?</Text> </View> </View> ))} <Button onPress={addNewEmail} title="+ Email" /> </View> </> );}任何幫助將不勝感激!
通過在 React Native 上切換 Switch 組件來更新數組狀態中的值
絕地無雙
2022-08-27 09:20:29