首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

为chakra-ui上的Modal创建变体样式

在 Chakra UI 中,你可以使用 extendTheme 函数来创建自定义的组件变体样式。以下是一个示例,展示如何为 Modal 组件创建变体样式。

步骤 1: 安装 Chakra UI

如果你还没有安装 Chakra UI,可以使用以下命令进行安装:

代码语言:javascript
复制
npm install @chakra-ui/react @emotion/react @emotion/styled framer-motion

步骤 2: 创建自定义主题

在你的项目中创建一个自定义主题文件,例如 theme.js,并在其中定义 Modal 组件的变体样式。

代码语言:javascript
复制
// theme.js
import { extendTheme } from "@chakra-ui/react";

const theme = extendTheme({
  components: {
    Modal: {
      // 定义全局样式
      baseStyle: {
        dialog: {
          borderRadius: "md",
          boxShadow: "lg",
        },
      },
      // 定义变体样式
      variants: {
        customVariant: {
          dialog: {
            bg: "teal.500",
            color: "white",
            borderRadius: "xl",
            boxShadow: "2xl",
          },
          header: {
            bg: "teal.600",
            color: "white",
          },
          footer: {
            bg: "teal.600",
            color: "white",
          },
        },
      },
    },
  },
});

export default theme;

步骤 3: 应用自定义主题

在你的应用程序入口文件中(例如 index.jsApp.js),使用 ChakraProvider 来应用自定义主题。

代码语言:javascript
复制
// index.js 或 App.js
import React from "react";
import ReactDOM from "react-dom";
import { ChakraProvider } from "@chakra-ui/react";
import App from "./App";
import theme from "./theme";

ReactDOM.render(
  <ChakraProvider theme={theme}>
    <App />
  </ChakraProvider>,
  document.getElementById("root")
);

步骤 4: 使用自定义变体样式

在你的组件中使用 Modal 组件,并应用自定义的变体样式。

代码语言:javascript
复制
// App.js
import React from "react";
import {
  Button,
  Modal,
  ModalOverlay,
  ModalContent,
  ModalHeader,
  ModalFooter,
  ModalBody,
  ModalCloseButton,
  useDisclosure,
} from "@chakra-ui/react";

function App() {
  const { isOpen, onOpen, onClose } = useDisclosure();

  return (
    <div>
      <Button onClick={onOpen}>Open Modal</Button>

      <Modal isOpen={isOpen} onClose={onClose} variant="customVariant">
        <ModalOverlay />
        <ModalContent>
          <ModalHeader>Custom Modal</ModalHeader>
          <ModalCloseButton />
          <ModalBody>
            This is a custom modal with a teal background and white text.
          </ModalBody>
          <ModalFooter>
            <Button colorScheme="teal" mr={3} onClick={onClose}>
              Close
            </Button>
            <Button variant="ghost">Secondary Action</Button>
          </ModalFooter>
        </ModalContent>
      </Modal>
    </div>
  );
}

export default App;

解释

  1. 自定义主题:在 theme.js 文件中,我们使用 extendTheme 函数来扩展 Chakra UI 的默认主题。我们为 Modal 组件定义了一个名为 customVariant 的变体样式。
  2. 应用自定义主题:在应用程序入口文件中,我们使用 ChakraProvider 组件来应用自定义主题。
  3. 使用自定义变体样式:在 App.js 文件中,我们使用 Modal 组件,并通过 variant 属性应用自定义的变体样式 customVariant
页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的合辑

领券