【问题标题】:Changing text color on click with react hooks使用反应挂钩更改单击时的文本颜色
【发布时间】:2020-07-27 10:16:58
【问题描述】:

我有一个简单的部分,用户可以在其中单击按钮,现在我想单击以使用反应钩子更改(切换)文本的颜色,这就是我目前所拥有的。'

const [textColor, setTextColor] = useState('black');

 const handleChnageTextColor = (e) => {
    setTextColor('#CCCCCC');
}

return(
<>
<label onClick={handleChnageTextColor} className="switch">
        <input type="checkbox" />
        <span className="slider round" />
</label>

 <small style={{ color:textColor}} className="switch-container_text">advanced view</small>
</>
)

所以点击时初始颜色为黑色我现在将颜色更改为#CCCCCC,当我再次点击时颜色没有改变。

我需要添加什么才能在点击时在这两种颜色之间切换?

【问题讨论】:

    标签: javascript html css reactjs


    【解决方案1】:

    将您的 handleChangeTextColor 更改为以下内容:

    const handleChnageTextColor = (e) => {
    
     setTextColor(textColor === 'black' ? '#CCCCCC' : 'black');
    }
    

    【讨论】:

    • 这不起作用,颜色根本没有改变
    【解决方案2】:

    您应该为复选框的值分配一些状态变量,并使文本的颜色取决于复选框的值。 以下肯定会帮助您达到预期的结果。

    const [textColor, setTextColor] = useState('black');
    const [isBlack, setIsBlack] = useState(true);
    
    const handleChnageTextColor = (e) => {
      setIsBlack(!isBlack);
      setTextColor(isBlack ? '#CCCCCC' : 'black ');
    }
    
    return(
      <>
       <label className="switch">
         <input type="checkbox" value={isBlack} onChange={handleChnageTextColor} />
         <span className="slider round" />
       </label>
       <small style={{ color:textColor}} className="switch-container_text">advanced view</small>
      </>
     )
    }
    

    【讨论】:

      【解决方案3】:

      您应该检查元素样式值以确定要应用的颜色:

      if(e.style.color === "black") '#CCCCCC' : 'black'
      

      【讨论】:

      • 这也不起作用,即使我得到未定义的错误颜色
      猜你喜欢
      • 1970-01-01
      • 2021-03-17
      • 2021-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-20
      • 2023-03-09
      相关资源
      最近更新 更多