Typescript React - 使用道具的样式化组件条件样式不起作用
Typescript React - Styled component conditional styling using prop not working
我正在尝试使用 useState
挂钩和样式组件更改按钮的颜色。
当我单击按钮时,selected
属性 会发生变化,但不会应用颜色。
按钮:
{toggleFilter.map((item) => {
return (
<FilterButton
key={`${item.name}FilterButton`}
$selected={item.selected}
onClick={() => handleToggleFilter(item)}
>
{item.name}
</FilterButton>
);
})}
样式化组件:
export const FilterButton = styled.button<{ $selected: boolean }>`
background-color: ${({ $selected }) => ($selected ? "#a144d5" : "#848485")};
transition: 0.3s ease-in-out;
color: white;
padding: 0.25rem 0.5rem;
margin: 0.5rem 0.1rem;
border: none;
`;
处理程序:
const handleToggleFilter = (item: ToggleFilterItem) => {
toggleFilter.forEach((i) => {
if (i.name === item.name) {
i.selected = !i.selected;
}
});
setToggleFilter(toggleFilter);
};
你正在改变状态,它应该被视为不可变的,尝试:
const handleToggleFilter = (item: ToggleFilterItem) => {
setToggleFilter(
toggleFilter.map((i) =>
i.name === item.name ? { ...i, selected: !i.selected } : i
)
);
};
我正在尝试使用 useState
挂钩和样式组件更改按钮的颜色。
当我单击按钮时,selected
属性 会发生变化,但不会应用颜色。
按钮:
{toggleFilter.map((item) => {
return (
<FilterButton
key={`${item.name}FilterButton`}
$selected={item.selected}
onClick={() => handleToggleFilter(item)}
>
{item.name}
</FilterButton>
);
})}
样式化组件:
export const FilterButton = styled.button<{ $selected: boolean }>`
background-color: ${({ $selected }) => ($selected ? "#a144d5" : "#848485")};
transition: 0.3s ease-in-out;
color: white;
padding: 0.25rem 0.5rem;
margin: 0.5rem 0.1rem;
border: none;
`;
处理程序:
const handleToggleFilter = (item: ToggleFilterItem) => {
toggleFilter.forEach((i) => {
if (i.name === item.name) {
i.selected = !i.selected;
}
});
setToggleFilter(toggleFilter);
};
你正在改变状态,它应该被视为不可变的,尝试:
const handleToggleFilter = (item: ToggleFilterItem) => {
setToggleFilter(
toggleFilter.map((i) =>
i.name === item.name ? { ...i, selected: !i.selected } : i
)
);
};