簡體   English   中英

在 React Native 中單擊時如何使每個按鈕更改顏色?

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

我在我的應用程序上使用 5 個不同的 colors 渲染 5 個按鈕,但是當我單擊一個按鈕時,所有按鈕都變為相同的顏色。 我只想更改我單擊的按鈕的 state,其他按鈕保持默認顏色。

我非常感謝您的幫助。 下面是代碼:

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>
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM