简体   繁体   English

如何更改颜色按钮 onclick react.js

[英]How to change color button onclick react.js

I work with buttons, and on click i need to change color button.我使用按钮,单击时我需要更改颜色按钮。

I have two button: favorite and stats, and onclick i need to change to custom color, for ex favorite is orange, stats blue.我有两个按钮:收藏和统计,以及 onclick 我需要更改为自定义颜色,因为前收藏是橙色,统计蓝色。

How i can change color onclick?如何更改颜色 onclick?

<div className={classes.fotter_button}>
                    <button>
                      <FontAwesomeIcon
                        icon={faStar}
                        aria-hidden="true"
                      />
                    </button>
                    <button>
                      <FontAwesomeIcon
                        icon={faChartBar}
                        aria-hidden="true"
                      />
                    </button>
                  </div>

One way is to add state variable in your component, and use a function to change the state variable between two values (true, false).一种方法是在组件中添加 state 变量,并使用 function 在两个值(真、假)之间更改 state 变量。 Apply the button styling based on the value of the state variable.根据 state 变量的值应用按钮样式。

const MyToggleButton = () => {
 const [toggle, setToggle] = React.useState(false);
 const toggleButton = () => setToggle(!toggle);
 
 return (
  <>
    <button style={{backgroundColor: toggle ? '#FFF' : '#000'}} onClick={toggleButton}>Click Me</button>
  </>
 );
}

My example is pretty generic;我的例子很笼统。 if possible consider using a state variable that more aptly describes your buttons two states.如果可能,请考虑使用 state 变量来更贴切地描述您的按钮两种状态。

const [favorite,setFavorite]=useState(false)
const [stats,setStats]=useState(false)

<div className={classes.fotter_button}>
                <button onClick={()=>{setFavorite(true)}} style={{backgroundColor:favorite==true?"orange":""}}>
                  <FontAwesomeIcon
                    icon={faStar}
                    aria-hidden="true"
                  />
                </button>
                <button onClick={()=>{setStats(true)}} style={{backgroundColor:stats==true?"blue":""}}>
                  <FontAwesomeIcon
                    icon={faChartBar}
                    aria-hidden="true"
                  />
                </button>
              </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM