英文:
How to revert the state of a button when clicked in a React component
问题
尝试在按钮被点击时恢复颜色和图标,但似乎无法找到处理状态的良好方法。
颜色和图标只改变一次,但再次点击后似乎无法恢复到原始状态。
我只想在每次点击时能够来回切换颜色和图标。
到目前为止,我尝试了以下方法...
英文:
Am trying to revert the color and icon of a button when clicked, but I can't seem to come up with a good approach to deal with the state
The the color and icon only change one time but can't seem to revert back to the original once clicked again
I just want to be able to switch the color and icon back and forth on every click
Here's what I've tried so far...
答案1
得分: 1
The issue is that your function is setting the icon to a tick and the color to green. Every time you click it, it will set it to the same value. I would remove both of these states and put only one - a boolean value that checks the state of the button. If it is true, the icon should be a tick, and the color should be green. If it is false - a cross and red.
const [isClicked, setIsClicked] = useState(false)
return (
<main>
<section
className={isClicked ? 'green' : 'red'}
onClick={() => setIsClicked(!isClicked)}
>
{isClicked ? 'tick' : 'cross'}
</section>
</main>
)
英文:
The issue is that your function is setting the icon to a tick and the color to green. Every time you click it it will set it to the same value. I would remove both of this states and put only one - boolean value that checks the state of the button. If it is true, the icon should be a tick and color should be green. If it is false - cross and red.
const [isClicked, setIsClicked] = useState(false)
return (
<main>
<section
className={isClicked ? 'green' : 'red'}
onClick={() => setIsClicked(!isClicked)}
>
{isClicked ? *tick* : *cross*}
</section>
</main>
)
答案2
得分: 0
这是您提供的JavaScript代码的中文翻译:
// 这是我刚想出的类似解决方案
function App() {
const [isOpen, setIsOpen] = useState(true);
const 切换符号 = () => {
setIsOpen(s => !s);
}
return (
<>
{
isOpen ?
<main>
<section className="red" onClick={切换符号}>✖</section>
</main>
: <main>
<section className="green" onClick={切换符号}>✔</section>
</main>
}
</>
)
}
如果您需要更多帮助或有其他问题,请随时告诉我。
英文:
// Here's a similar solution I just came up with
function App() {
const [isOpen, setIsOpen] = useState(true);
const symbol = () => {
setIsOpen(s => !s);
}
return (
<>
{
isOpen ?
<main>
<section className="red" onClick={symbol}>✖</section>
</main>
: <main>
<section className="green" onClick={symbol}>✔</section>
</main>
}
</>
)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论