我想在默认颜色和"blue"颜色之间切换,当我在 ReactJS 中单击按钮时



我想切换h1标记的颜色。我可以将颜色一次性更改为特定颜色。但我想在再次单击时将颜色恢复为以前的颜色。为此,我使用了useState。在useState中,选择给我的是真和假。根据true和false,我创建if语句并更改颜色。这是我的代码

import './App.css';
import React, { useState } from 'react';
function Deneme() {
const [color,setColor]=useState('red');
const [selected, setSelected] = useState(false)
const [textColor,setTextColor]=useState('white');
if(!selected){
setColor("blue")
}
return (
<div className="App">
<button style={{background:color}} className='btn btn-primary' onClick={()=>{setTextColor('red');setSelected(!selected)}}>Click here</button>
<h1 style={{color:color}}>Change Color</h1>
</div>
);
}
export default Deneme;
import {useState} from 'react';
export default function App() {
const [color,setColor]=useState(true);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<button onClick={()=>setColor(!color)}
style={{color:color ? 'red':'blue'}}>clickme</button>
</div>

);}

只需创建一个布尔状态,并在布尔值的基础上将颜色更改为红色或蓝色。

如果您想在特定状态更改时执行任何操作,则不能在此处放置if语句,而是使用useEffect。https://reactjs.org/docs/hooks-effect.html

但在你的情况下,我认为useEffect没有必要。

我用工作代码创建了一个CodeSandboxhttps://codesandbox.io/s/reactjs-playground-forked-pdpvq?file=/src/index.js

最新更新