简体   繁体   English

根据状态或单击事件更改文本颜色

[英]Change text color based on state or click event

Im having problem changing text color based on either the count is increasing or decreasing while also having the ability to change color through click event, how do I solve this.我在根据计数增加或减少更改文本颜色时遇到问题,同时还可以通过单击事件更改颜色,我该如何解决这个问题。 Sorry Im new to react.对不起,我是新来的反应。

import React, {useState, useEffect} from 'react';

function Counter() {
  const [count, setCount] = useState(0)
  const increase = () => setCount(count + 1);
  const decrease = () => setCount(count - 1);
  const [prevCount, setPrevCount] = useState(count);
  const [color, setColor] = useState('yellow')

  useEffect(() => {
    if (count > prevCount) {
      setPrevCount(count - 1);
    }
  }, [count])

 function handleColorChange() {
      const nextColor = color ==='green'? "red" : "green"
      setColor(nextColor)
 }

  return (
    <div className="App">
      {console.log(prevCount)}
      <button  onClick={increase}>
         increase
      </button>
      <button onClick={handleColorChange}>
         toggle color
      </button>
      <button disabled={count <= 0} onClick={decrease}>
         decrease
      </button>
      <br/>
      <p style={{color, fontSize: "20px", fontWeight: "bold"}}>{count}</p>
    </div>
  );
}

export default Counter;

Based on your explanation, why don't you just configure the increase function to set the color to green, and the decrease to red?根据您的解释,您为什么不直接配置increase功能,将颜色设置为绿色,将decrease为红色?

  const increase = () => {
    setCount(count + 1);
    setColor("green");
  };
  const decrease = () => {
    setCount(count - 1);
    setColor("red");
  };

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

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