按下按钮时更改颜色并取消选择其他选项

change color when button is pressed and deselect other options

我有 5 个用 touchableopacity 包装的选项。我希望当单击一个选项时颜色变为绿色。如果我单击另一个选项,则前一个选项变为灰色,新选项为绿色。有人可以帮我编码吗?我不想写一堆 IF 语句。我觉得它的代码很糟糕,而且有一种更快的方法可以达到我的目标。不要介意那里的警报功能,我只有在最初设置可触摸不透明度时才有。

const [angryColor, setAngryColor] = useState('grey')
    const [sadColor, setEmojiSad] = useState('grey')
    const [neutral, setNuetral] = useState('grey')
    const [happyColor, setHappyColor] = useState('grey')
    const [laughColor, setLaugh] = useState('grey')

 function toggleAngry(){
     if (angryColor === 'grey'){
         setAngryColor('green')
     } else {
         setAngryColor('grey')
     }
    }


    return(
        <View style={styles.screen}>
            <View style={styles.container}>
                <View style={styles.emojiView}>
                    <TouchableOpacity onPress={() => toggleAngry()}>
                        <FontAwesome5 name="angry" size={40} color={angryColor}/>
                    </TouchableOpacity>
                    <TouchableOpacity onPress={() => Alert.alert('clicked')}>
                        <Entypo name="emoji-sad" size={40} color={sadColor}/>
                    </TouchableOpacity>
                    <TouchableOpacity onPress={() => Alert.alert('clicked')}>
                        <Entypo name="emoji-neutral" size={40} color={neutral} />
                    </TouchableOpacity>
                    <TouchableOpacity onPress={() => Alert.alert('clicked')}>
                        <Entypo name="emoji-happy" size={40} color={happyColor}/>
                    </TouchableOpacity>
                    <TouchableOpacity onPress={() => Alert.alert('clicked')}>
                        <FontAwesome5 name="laugh-beam" size={40} color={laughColor} />
                    </TouchableOpacity>
                </View>

您可以设置单个变量并以此为基础设置颜色。不需要多个状态。我添加了一个回调函数,父组件可以使用它来获取此更新。

const EmojiInput = (props) => {
  const [selected, setSelected] = React.useState(0);

  const onItemSelected=emoji=>{
    setSelected(emoji);
    if(props.callback){
      props.callback(emoji);
    }
  };

  return (
    <View style={styles.emojiView}>
      <TouchableOpacity onPress={() => onItemSelected(1)}>
        <FontAwesome5 name="angry" size={40} color={selected==1?'red':'grey'} />
      </TouchableOpacity>
      <TouchableOpacity onPress={() => onItemSelected(2)}>
        <Entypo name="emoji-sad" size={40} color={selected==2?'red':'grey'} />
      </TouchableOpacity>
      <TouchableOpacity onPress={() => onItemSelected(3)}>
        <Entypo name="emoji-neutral" size={40} color={selected==3?'red':'grey'} />
      </TouchableOpacity>
      <TouchableOpacity onPress={() => onItemSelected(4)}>
        <Entypo name="emoji-happy" size={40} color={selected==4?'red':'grey'} />
      </TouchableOpacity>
      <TouchableOpacity onPress={() => onItemSelected(5)}>
        <FontAwesome5 name="laugh-beam" size={40} color={selected==5?'red':'grey'} />
      </TouchableOpacity>
    </View>
  );
};