如果选择和取消选择按钮,如何更改按钮颜色

How to make button color change if button selected and unselected

我需要帮助来添加一项功能,比如如果用户单击按钮,它会将按钮的颜色更改为 danger,这样感觉就像它被选中,如果用户单击相同的按钮它应该回到原来的颜色 primary.

我也想让它有点动态,这样它应该知道在映射对象中选择了哪个按钮。

我现在有以下代码。

       <Row xs={3} md={4} className="g-3 py-2 px-2">
          {data.map((postData) => {
            return (
              <Button
                className="mx-2"
                style={{
                  width: "10rem",
                  height: "13rem",
                  lineHeight: "14px",
                  fontSize: "12px"
                }}
                key={postData.id}
              >
                <Card.Img variant="top" src={postData.image} />
                <Card.Body>
                  <Card.Title className={style.tile}>
                    {postData.title}
                  </Card.Title>
                </Card.Body>
              </Button>
            );
          })}
        </Row>

It's also running in the CodeSandBox

能否告诉我如何处理这个问题?

我尝试为此目的使用 useState

onClick={() => setCls((cls) => (cls === "red" ? "green" : "red"))

但是这会一键更改所有按钮的颜色,您可以在 codesandbox 中看到它。

试试这个代码:

import React, { useState } from "react";

//react bootstrap components
import { Container, Row, Card, Button } from "react-bootstrap";

//scss
import style from "./styles.module.scss";

//data for post
import data from "./data.json";

const App = () => {
  const [selectedBtnList,  setSelectedBtnList] = useState([])

const selectBtnAddHandler = (btnId) => {
 const isInList = selectedBtnList.some(item => item === btnId)
 if(isInList){
  setSelectedBtnList(selectedBtnList.filter(item => item !== btnId))
 }else {
  setSelectedBtnList([...selectedBtnList,btnId])
 }
}
  return (
    <>
      <Container fluid={true}>
        <Row xs={3} md={4} className="g-3 py-2 px-2">
          {data.map((postData) => {
            return (
              <Button
                className="mx-2"
                style={{
                  width: "10rem",
                  height: "13rem",
                  lineHeight: "14px",
                  fontSize: "12px"
                }}
                key={postData.id}
                variant={selectedBtnList.includes(postData.id) ? "danger" : "primary"}
                onClick={()=> selectBtnAddHandler(postData.id)}
              >
                <Card.Img variant="top" src={postData.image} />
                <Card.Body>
                  <Card.Title className={style.tile}>
                    {postData.title}
                  </Card.Title>
                </Card.Body>
              </Button>
            );
          })}
        </Row>
      </Container>
    </>
  );
};

export default App;