Toast 消息提示组件 #
基本用法 #
jsx
import { useToast, Button } from '@chakra-ui/react'
function Example() {
const toast = useToast()
return (
<Button
onClick={() =>
toast({
title: '操作成功',
description: '您的更改已保存',
status: 'success',
duration: 3000,
isClosable: true,
})
}
>
显示 Toast
</Button>
)
}
状态类型 #
jsx
const toast = useToast()
toast({ title: '成功', status: 'success' })
toast({ title: '错误', status: 'error' })
toast({ title: '警告', status: 'warning' })
toast({ title: '信息', status: 'info' })
位置 #
jsx
toast({ title: '顶部', position: 'top' })
toast({ title: '右上', position: 'top-right' })
toast({ title: '右下', position: 'bottom-right' })
toast({ title: '底部', position: 'bottom' })
toast({ title: '左下', position: 'bottom-left' })
toast({ title: '左上', position: 'top-left' })
配置选项 #
jsx
toast({
title: '账户已创建',
description: '我们已为您创建了账户',
status: 'success',
duration: 5000,
isClosable: true,
position: 'top-right',
variant: 'subtle',
})
自定义渲染 #
jsx
toast({
position: 'bottom-right',
render: () => (
<Box color="white" p={3} bg="blue.500" borderRadius="md">
自定义 Toast 内容
</Box>
),
})
更新和关闭 #
jsx
function ToastExample() {
const toast = useToast()
const toastIdRef = useRef()
const addToast = () => {
toastIdRef.current = toast({
title: '处理中...',
status: 'loading',
duration: null,
})
}
const updateToast = () => {
if (toastIdRef.current) {
toast.update(toastIdRef.current, {
title: '处理完成',
status: 'success',
duration: 3000,
})
}
}
const closeToast = () => {
if (toastIdRef.current) {
toast.close(toastIdRef.current)
}
}
return (
<HStack>
<Button onClick={addToast}>显示</Button>
<Button onClick={updateToast}>更新</Button>
<Button onClick={closeToast}>关闭</Button>
</HStack>
)
}
关闭所有 Toast #
jsx
function CloseAllExample() {
const toast = useToast()
return (
<HStack>
<Button
onClick={() => {
toast({ title: 'Toast 1' })
toast({ title: 'Toast 2' })
toast({ title: 'Toast 3' })
}}
>
显示多个
</Button>
<Button onClick={() => toast.closeAll()}>
关闭所有
</Button>
</HStack>
)
}
实用示例 #
表单提交 #
jsx
function FormWithToast() {
const toast = useToast()
const handleSubmit = async () => {
try {
await submitForm()
toast({
title: '提交成功',
description: '您的表单已成功提交',
status: 'success',
duration: 3000,
isClosable: true,
})
} catch (error) {
toast({
title: '提交失败',
description: error.message,
status: 'error',
duration: 5000,
isClosable: true,
})
}
}
return <Button onClick={handleSubmit}>提交</Button>
}
复制成功 #
jsx
function CopyButton({ text }) {
const toast = useToast()
const handleCopy = () => {
navigator.clipboard.writeText(text)
toast({
title: '已复制',
status: 'success',
duration: 2000,
})
}
return (
<Button size="sm" onClick={handleCopy}>
复制
</Button>
)
}
Toast 属性速查表 #
| 属性 | 说明 | 值 |
|---|---|---|
| title | 标题 | string |
| description | 描述 | string |
| status | 状态 | success, error, warning, info |
| duration | 持续时间 | number (ms) |
| position | 位置 | top, top-right, bottom… |
| isClosable | 可关闭 | boolean |
| variant | 变体 | solid, subtle, left-accent |
下一步 #
现在你已经掌握了 Toast 组件,接下来学习 Modal 对话框,了解如何使用模态对话框!
最后更新:2026-03-28