在 React Native 中如何让每个按钮在点击时改变颜色?

How to make each button chnage color when clicked in React Native?

我在我的应用程序上渲染了 5 个按钮,使用 5 种不同的颜色,但是当我单击一个按钮时,所有按钮都变为相同的颜色。我只想更改我正在单击的按钮的状态,其他按钮保持默认颜色。

非常感谢您的帮助。这是下面的代码:

const buttonArray = [
        { value: 'red', name: 'tomato' },
        { value: 'green', name: 'apple' },
        { value: 'blue', name: 'berry' },
        { value: 'yellow', name: 'banana' },
        { value: 'orange', name: 'orange' }
    ]

    const [buttonCol, setButtonCol] = useState(null)
    const [isSelected, setIsSelected] = useState(false)

    function selectedBtn(index) {
        buttonArray.map((btn, ind) => {
            if (buttonArray.indexOf(btn) === index) {
                setIsSelected(!isSelected)
                setButtonCol(btn.value)
            }
        })
    }

return(
<View style={styles.button}>
       { buttonArray.map((button, index) => {
           return (
            <TouchableOpacity
              style={[globalStyles.selectButton, isSelected ? { backgroundColor: buttonCol } : { backgroundColor: globalColors.iconGreyColor }]}
               onPress={() =>  selectedBtn(index) }>
                      <Text style={{ color: '#fff' }}>{button.name}</Text>
            </TouchableOpacity>
          )})
   }
</View>
)

记录 selectedIndex 而不仅仅是 selected 标志

  const [selectedIndex, setSelectedIndex] = useState(-1);

  return (
    <View style={styles.button}>
      {buttonArray.map((button, index) => {
        return (
          <TouchableOpacity
            style={[
              globalStyles.selectButton,
              selectedIndex === index
                ? {backgroundColor: buttonArray[index].value}
                : {backgroundColor: globalColors.iconGreyColor},
            ]}
            onPress={() => setSelectedIndex(index)}>
            <Text style={{color: '#fff'}}>{button.name}</Text>
          </TouchableOpacity>
        );
      })}
    </View>
  );

这可能有帮助

const buttonArray = [...];

const [buttonCol, setButtonCol] = useState(null);
const [isSelected, setIsSelected] = useState(false);
const [data, setData] = useState(buttonArray); // New Added

function selectedBtn(index) {
  const newData = [...data];
  newData[index].isSelected = newData[index].isSelected ? false : true;
  setData(newData);
}

return (
  <View style={styles.button}>
    {data.map((button, index) => {
      return (
        <TouchableOpacity
          style={[
            globalStyles.selectButton,
            button.isSelected
              ? { backgroundColor: buttonCol }
              : { backgroundColor: globalColors.iconGreyColor },
          ]}
          key={button.value} // add key here
          onPress={() => selectedBtn(index)}
        >
          <Text style={{ color: "#fff" }}>{button.name}</Text>
        </TouchableOpacity>
      );
    })}
  </View>
);