0

当我按下按钮时,我有 5 个按钮“35,17,11,8,5”我想将按钮的值添加到数组中,并将按钮的背景颜色设置为“绿色”,如果我再次按下它,删除按钮的值从数组中并将按钮的背景颜色设置为“白色”,所以我这样做了。

import React, { useState } from "react";
import { StyleSheet, Text, View, Pressable, TextInput } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';

function RouletteExercice1 ({ navigation }){

const [multiplyArray, setMultiplyArray] = useState([]);

function AddtoArray(value){
  if (multiplyArray.includes(value)) {
       multiplyArray.splice(multiplyArray.indexOf(value),1);
       console.log(multiplyArray);
     } else {
       setMultiplyArray((prev) => [...prev, value]);
     }
};

  return(
    <View>
          <Pressable style={multiplyArray.includes(35) ? styles.buttonRE1green : styles.buttonRE1} onPress={() => {AddtoArray(35)}}>
            <Text>35</Text>
          </Pressable>
          <Pressable style={multiplyArray.includes(17) ? styles.buttonRE1green : styles.buttonRE1} onPress={() => {AddtoArray(17)}}>
            <Text>17</Text>
          </Pressable>
          <Pressable style={multiplyArray.includes(11) ? styles.buttonRE1green : styles.buttonRE1} onPress={() => {AddtoArray(11)}}>
            <Text>11</Text>
          </Pressable>
          <Pressable style={multiplyArray.includes(8) ? styles.buttonRE1green : styles.buttonRE1} onPress={() => {AddtoArray(8)}}>
            <Text>8</Text>
          </Pressable>
          <Pressable style={multiplyArray.includes(5) ? styles.buttonRE1green : styles.buttonRE1} onPress={() => {AddtoArray(5)}}>
            <Text>5</Text>
          </Pressable>
    </View>
  )

}

当我按下一个按钮它起作用时,值被添加到列表中并且按钮设置为绿色,我再次按下它从列表中删除值但不将按钮设置为白色,将其设置为白色的唯一方法是按另一个按钮。

Example:
Btn 35 pressed
35 added to list, Btn 35 set to 'green'
Btn 35 pressed
35 removed from the list
Btn 17 pressed
17 added to list, Btn 17 set to 'green', Btn 35 set to 'white'

有人可以告诉我有什么问题吗?请

4

0 回答 0