亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

通過在 React Native 上切換 Switch 組件來更新數組狀態中的值

通過在 React Native 上切換 Switch 組件來更新數組狀態中的值

絕地無雙 2022-08-27 09:20:29
我在 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>    </>  );}任何幫助將不勝感激!
查看完整描述

1 回答

?
幕布斯7119047

TA貢獻1794條經驗 獲得超8個贊

您只需要通過像這樣分散以前的數組來創建新數組


const setMainEmail = (value, emailIndex) => {

    const array = [...emails];

    console.log(array);

    array[emailIndex].main = value;

    console.log(array);

    setEmails(array);

  };

這是另一個方案工作和失敗的原因,你在添加新項的方案中做對了。


查看完整回答
反對 回復 2022-08-27
  • 1 回答
  • 0 關注
  • 191 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號