繁体   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