Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
294 views
in Technique[技术] by (71.8m points)

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

I am rendering 5 buttons with 5 different colors on my app but when I click one button, all buttons change to the same color. I would like to change only the state of the button I am clicking and other buttons remain the default color.

I would really appreciate your assistance. Here is the code below:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This might help

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...