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

时间:2019-08-24 06:41:51

标签: javascript reactjs react-hooks

我在基于计数增加或减少的同时更改文本颜色时遇到问题,同时还具有通过单击事件更改颜色的能力,我该如何解决。对不起,我是新来的。

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;

1 个答案:

答案 0 :(得分:1)

根据您的解释,为什么不只配置increase函数将颜色设置为绿色,将decrease设置为红色?

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