【问题标题】:Simple counter changing the color of counter value in react ja简单计数器改变反应js中计数器值的颜色
【发布时间】:2023-02-10 15:48:38
【问题描述】:

在计数器应用程序中,我希望计数器值的颜色应为(如果计数器> 0-值应显示为“绿色”并且计数器<0值应显示为“红色”

【问题讨论】:

  • 你能分享你已经拥有的代码吗?
  • 我使用了 classNames 包,但我需要代码而不使用 classNames src.zip (file://DESKTOP-PH4BJ42/Users/user/counter/src.zip)

标签: html class styles


【解决方案1】:

您可以为此使用 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添加了一个基本的三元运算符

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-18
    • 1970-01-01
    • 2015-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多