【发布时间】:2023-02-10 15:48:38
【问题描述】:
在计数器应用程序中,我希望计数器值的颜色应为(如果计数器> 0-值应显示为“绿色”并且计数器<0值应显示为“红色”
【问题讨论】:
-
你能分享你已经拥有的代码吗?
-
我使用了 classNames 包,但我需要代码而不使用 classNames src.zip (file://DESKTOP-PH4BJ42/Users/user/counter/src.zip)
在计数器应用程序中,我希望计数器值的颜色应为(如果计数器> 0-值应显示为“绿色”并且计数器<0值应显示为“红色”
【问题讨论】:
您可以为此使用 Hooks useEffect。
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
});
return (
<div className={`${(count <= 0) ? "red" : "green"}`}>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
我只是跟着official documentation添加了一个基本的三元运算符
【讨论】: