猿问

通过在 React Native 上切换 Switch 组件来更新数组状态中的值

我在 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>

    </>

  );

}

任何帮助将不胜感激!


绝地无双
浏览 205回答 1
1回答

幕布斯7119047

您只需要通过像这样分散以前的数组来创建新数组const setMainEmail = (value, emailIndex) => {&nbsp; &nbsp; const array = [...emails];&nbsp; &nbsp; console.log(array);&nbsp; &nbsp; array[emailIndex].main = value;&nbsp; &nbsp; console.log(array);&nbsp; &nbsp; setEmails(array);&nbsp; };这是另一个方案工作和失败的原因,你在添加新项的方案中做对了。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答