动态换肤过渡

127 阅读1分钟

问题

点击开关进行主题切换会出现各个部分颜色变换不同步的情况。

代码

  • App.tsx
import "./styles.css";

import React, { useState } from "react";

import { Layout, Row, Col, Switch, Menu } from "antd";

const { Header, Content, Sider } = Layout;

const items = [

{ label: "菜单项一", key: "item-1" }, // 菜单项务必填写 key

{ label: "菜单项二", key: "item-2" },

{

label: "子菜单",

key: "submenu",

children: [{ label: "子菜单项", key: "submenu-item-1" }]

}

];

export default function App() {

const [theme, setTheme] = useState<"dark" | "light">("dark");

const changeTheme = (value: boolean) => {

setTheme(value ? "dark" : "light");

};

return (

<Layout style={{ minHeight: "100vh" }} className="layout">

<Sider theme={theme}>

<div className={`${theme}`}>hhhhhhhh</div>

<Menu items={items} mode="inline" theme={theme} />

</Sider>

<Layout>

<Header className={`${theme}`}>

<Row align="middle" justify="space-between">

<Col>

<Switch

checked={theme === "dark"}

onChange={changeTheme}

checkedChildren="dark"

unCheckedChildren="light"

/>

</Col>

<Col>

<h1 className={`${theme}`}>hello</h1>

</Col>

</Row>

</Header>

<Content style={{ margin: "0 16px" }}>Content</Content>

</Layout>

</Layout>

);

}
  • style.css
.dark {

background-color: #001529;

color: snow;
}
.light {

background-color: #fff;

color: black;

}

原因

.ant-menu有过渡效果,其他部分没有,所以会看起来不同步

transition: background 0.3s, width 0.3s cubic-bezier(0.2, 0, 0, 1) 0s;

transition-property: background, width;

transition-duration: 0.3s, 0.3s;

transition-timing-function: ease, cubic-bezier(0.2, 0, 0, 1);

transition-delay: 0s, 0s;

总结

  • 可用transition实现主题切换的过渡效果
  • 样式不同步问题优先排查transition和animation