单击按钮时,我在div 中添加或删除类名"a"。它变为50px宽度,但没有过渡
const Navbar = ({ size }) => {
const MobileNavigation = styled.nav`
div {
width: 100px;
height: 100px;
background-color: blue;
transition: width 1s;
&.a {
width: 50px;
}
}
`;
const [active, setActive] = useState(0);
if (size.width < 500 || (size.width > size.height && size.width < 800)) {
return (
<MobileNavigation>
<button
onClick={() => {
if (active) {
setActive(false);
} else {
setActive(true);
}
}}
>
button
</button>
<div className={active ? 'a' : ''}></div>
</MobileNavigation>
}
);
export default withSize()(Navbar);
如何使用过渡向此元素添加类?谢谢!
您的样式组件需要移动到NavBar
之外。每次NavBar
重新渲染时,您都在创建一个全新的MobileNavigation
组件,而该新组件不知道它应该从以前的width
转换
const MobileNavigation = styled.nav`
div {
width: 100px;
height: 100px;
background-color: blue;
transition: width 1s;
&.a {
width: 50px;
}
}
`;
const Navbar = ({ size }) => {
const [active, setActive] = useState(false);
if (size.width < 500 || (size.width > size.height && size.width < 800)) {
return (
<MobileNavigation>
<button
onClick={() => {
if (active) {
setActive(prevState => !prevState);
} else {
setActive(prevState => !prevState);
}
}}
>
button
</button>
<div className={active ? "a" : ""} />
</MobileNavigation>
);
}
return null;
};
export default withSize()(Navbar);