我使用 Chakra UI,并且我的应用程序中有几个 Toast 组件。默认情况下,它们的背景颜色为蓝色,因为它们具有
status="info"
。
如何使用
status="info"
更改所有吐司的背景颜色?我想保留所有其他默认样式(宽度、位置等),只需要更改颜色。
Toast
组件在底层使用Alert
。
Alert
将 status
属性映射到配色方案。此配色方案在主题定义中用于定义背景颜色。
默认情况下,
status="info"
映射到blue
并使用subtle
变体。
编辑(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 的新版本中,Toast 确实在幕后使用警报,但他们已从微妙转向使用警报的实体变体。设计 Alert 的实体变体将会设计您的 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"
/>
),
});
在扩展主题中,你必须更改警报的样式,这是我的解决方案并且有效
const 主题 = 扩展主题( {
components: {
Alert: {
variants: {
"left-accent": (props:any) => {
const { status } = props
return {
container: {
...theme.components.Alert.variants?.["left-accent"](props).container,
bg: `${status}.300`,
},
}
}
}
}
}
},