如何更改Chakra UI Toast组件的背景颜色?



我使用Chakra UI,在我的应用程序中有几个Toast组件。它们默认的背景颜色是蓝色的,因为它们有status="info"

如何使用status="info"更改所有祝酒词的背景颜色?我想保留所有其他默认样式(宽度,位置等),只需要改变颜色。

Toast组件在引擎盖下使用Alert

Alertstatus道具映射到一个配色方案。这个配色方案在主题定义中用于定义背景色。

默认情况下,status="info"映射到blue,使用subtle的变体。

EDIT (Chakra>= 2.0)Toast现在默认使用solid变体。在下面的解决方案中,将subtle替换为solid以修改默认外观。

因此,您需要在主题定义中添加这样的覆盖:

import { theme as origTheme, extendTheme } from "@chakra-ui/react"
const theme = extendTheme({
components: {
Alert: {
variants: {
subtle: (props) => { // only applies to `subtle` variant
const { colorScheme: c } = props
if (c !== "blue") {
// use original definition for all color schemes except "blue"
return origTheme.components.Alert.variants.subtle(props)
}
return {
container: {
bg: `${c}.500`, // or literal color, e.g. "#0984ff"
},
}
}
}
}
}
})

blue.500这样的颜色变量从颜色定义中读取。

在较新的Chakra版本中,Toasts确实在底层使用警报,但他们已经从微妙的警报切换到使用固态的警报变体。为Alert的solid变体设置样式将为Toast设置样式。

您可以创建自己的toast组件包装器,如下所示

import { Flex, Heading, Text } from '@chakra-ui/react';
import React from 'react';
const BaseAlert = (props) => {
const { title, details, ...style } = props;
return (
<Flex
flexDirection="column"
alignItems="center"
justifyContent="center"
{...style}
py={4}
px={4}
borderLeft="3px solid"
borderRight="3px solid"
borderColor={`${style.colorScheme}.700`}
bgColor={`${style.colorScheme}.100`}
>
<Heading
as="h4"
fontSize="md"
fontWeight="500"
color={`${style.colorScheme}.800`}
>
{props.title}
</Heading>
{props.details ? (
<Text color={`${style.colorScheme}.800`}>{props.details}</Text>
) : null}
</Flex>
);
};
export const ErrorAlert = (props) => {
return <BaseAlert colorScheme="red" {...props} />;
};

像这样使用

toast({
render: () => (
<ErrorAlert
title="Impossible d'ajouter un nouveau moyen de paiement"
details="Veuillez ressayer ou nous contacter"
/>
),
});

最新更新