javascript - 根据状态或单击事件更改文本颜色
问题描述
我在根据计数增加或减少更改文本颜色时遇到问题,同时还能够通过单击事件更改颜色,我该如何解决这个问题。对不起,我是新来的反应。
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;
解决方案
根据您的解释,您为什么不直接配置increase
函数将颜色设置为绿色,并将颜色设置decrease
为红色?
const increase = () => {
setCount(count + 1);
setColor("green");
};
const decrease = () => {
setCount(count - 1);
setColor("red");
};