gpt4 book ai didi

javascript - React useState() bool 切换组件添加而不是替换值

转载 作者:行者123 更新时间:2023-12-04 07:12:49 26 4
gpt4 key购买 nike

我创建了一个模拟社交媒体网站,用户可以在其中评论和“喜欢”帖子,所以我想要一个带有竖起大拇指的按钮,可以在“喜欢”和“不喜欢”之间切换。问题是,当我单击时,状态值(不喜欢)由 setState 值(喜欢)代替替换。我哪里错了?

import React, { useState } from 'react';
import ThumbUpIcon from '@material-ui/icons/ThumbUp';

const ThumbUpButton = {
backgroundColor: 'rgb(115, 250, 179)',
border: 'none',
borderRadius: '5px',
}

const ThumbStyle = {
backgroundColor: 'red',
border: 'none',
padding: '5px',
borderRadius: '5px',
margin: '1rem'
}

const Liker = () => {
const [thumb, setThumbUp] = useState(false);

return (
<>
<button style={{border: 'none', backgroundColor: 'transparent'}} onClick={() => setThumbUp(!thumb)}>
<ThumbUpIcon style={ThumbStyle} />
{thumb && <ThumbUpIcon style={ThumbUpButton} />}
</button>
</>
);
}

export default Liker;

最佳答案

如果我理解您的问题,您会问为什么有时竖起大拇指和竖起大拇指会同时呈现。这是因为您无条件地将拇指向上渲染,并有条件地将拇指向下渲染。
您应该渲染其中一个。由于它是相同的组件并且您只是交换样式,因此有条件地应用一种或另一种样式。
此外,在切换 bool 状态值时通常使用功能状态更新,因为下一个状态必须取决于前一个状态,即 thumb => !thumb .这避免了回调中的陈旧状态 shell 。

<button
style={{
border: 'none',
backgroundColor: 'transparent'
}}
onClick={() => setThumbUp(thumb => !thumb)}
>
<ThumbUpIcon style={thumb ? ThumbStyle : ThumbUpButton} />
</button>

关于javascript - React useState() bool 切换组件添加而不是替换值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68968545/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com