"use client"
import { Button } from "@chakra-ui/react"
import { toaster } from "@/components/ui/toaster"
const Demo = () => {
return (
<Button
variant="outline"
size="sm"
onClick={() =>
toaster.create({
description: "File saved successfully",
type: "info",
})
}
>
Show Toast
</Button>
)
}
设置
¥Setup
如果你还没有该代码片段,请运行以下命令添加 toaster 代码片段。
¥If you don't already have the snippet, run the following command to add the
toaster snippet
npx @chakra-ui/cli snippet add toaster
该代码片段包含 Toast 组件的封闭组件组合。
¥The snippet includes a closed component composition for the Toast component.
用法
¥Usage
import { Toaster, toaster } from "@/components/ui/toaster"
首先,在你的应用中渲染 Toaster 组件。
¥First, render the Toaster component in your app.
<Toaster />
然后,通过调用 toaster 函数创建一个 Toast。
¥Then, create a toast by calling the toaster function.
toaster.create({
title: "Toast Title",
description: "Toast Description",
})
示例
¥Examples
可关闭的 Toast
¥Closable Toast
将 closable 属性设置为 true 可创建可关闭的提示框。
¥Set the closable prop to true to create a closable toast.
"use client"
import { Button } from "@chakra-ui/react"
import { toaster } from "@/components/ui/toaster"
const Demo = () => {
return (
<Button
variant="outline"
size="sm"
onClick={() =>
toaster.create({
description: "File saved successfully",
type: "info",
closable: true,
})
}
>
Show Toast
</Button>
)
}
外部关闭
¥External Close
使用 toaster.dismiss 方法关闭提示框。
¥Use the toaster.dismiss method to close a toast.
-
toaster.dismiss(id):通过其 ID 关闭提示框。 -
toaster.dismiss():关闭所有提示框。
"use client"
import { Button, HStack } from "@chakra-ui/react"
import { toaster } from "@/components/ui/toaster"
const Demo = () => {
return (
<HStack>
<Button
variant="outline"
size="sm"
onClick={() =>
toaster.create({
description: "File saved successfully",
type: "info",
})
}
>
Show Toast
</Button>
<Button variant="outline" size="sm" onClick={() => toaster.dismiss()}>
Close Toasts
</Button>
</HStack>
)
}
类型
¥Types
以下是每种吐司的示例。
¥Here's an example of each type of toast.
"use client"
import { Button, For, HStack } from "@chakra-ui/react"
import { toaster } from "@/components/ui/toaster"
const Demo = () => {
return (
<HStack>
<For each={["success", "error", "warning", "info"]}>
{(type) => (
<Button
size="sm"
variant="outline"
key={type}
onClick={() =>
toaster.create({
title: `Toast status is ${type}`,
type: type,
})
}
>
{type}
</Button>
)}
</For>
</HStack>
)
}
包含动作
¥With Action
使用 action 和 actionLabel 属性,在提示框中添加操作。
¥Use the action and actionLabel prop to add an action to the toast.
点击操作触发器时,toast 将会关闭。
"use client"
import { Button } from "@chakra-ui/react"
import { toaster } from "@/components/ui/toaster"
const Demo = () => {
return (
<Button
variant="outline"
size="sm"
onClick={() =>
toaster.success({
title: "Update successful",
description: "File saved successfully to the server",
action: {
label: "Undo",
onClick: () => console.log("Undo"),
},
})
}
>
Click me
</Button>
)
}
持久提示框
¥Persistent Toast
将 type 属性设置为 "loading" 可创建持久的提示框。
¥Set the type prop to "loading" to create a persistent toast.
"use client"
import { Button } from "@chakra-ui/react"
import { toaster } from "@/components/ui/toaster"
const Demo = () => {
return (
<Button
variant="outline"
size="sm"
onClick={() =>
toaster.create({
description: "File saved successfully",
type: "loading",
})
}
>
Show Toast
</Button>
)
}
Promise
使用 toaster.promise 创建一个在 Promise 解析后解析的 Toast。
¥Use the toaster.promise to create a toast that resolves when the promise is
resolved.
接下来,你可以为 Promise 的每个状态定义提示框选项(标题、描述等)。
¥Next, you can define the toast options (title, description, etc.) for each state of the promise.
"use client"
import { Button } from "@chakra-ui/react"
import { toaster } from "@/components/ui/toaster"
const Demo = () => {
return (
<Button
variant="outline"
size="sm"
onClick={() => {
const promise = new Promise<void>((resolve) => {
setTimeout(() => resolve(), 5000)
})
toaster.promise(promise, {
success: {
title: "Successfully uploaded!",
description: "Looks great",
},
error: {
title: "Upload failed",
description: "Something wrong with the upload",
},
loading: { title: "Uploading...", description: "Please wait" },
})
}}
>
Show Toast
</Button>
)
}
更新
¥Update
使用 toaster.update(...) 修改可见的 Toast。
¥Use toaster.update(...) to modify a visible toast.
"use client"
import { Button, HStack } from "@chakra-ui/react"
import { toaster } from "@/components/ui/toaster"
const Demo = () => {
const id = "login-error-toast"
const show = () => {
if (toaster.isVisible(id)) return
toaster.loading({
id,
title: "Error Connecting...",
description: "You do not have permissions to perform this action.",
})
}
const update = () => {
toaster.update(id, {
title: "Hooray 🥳🥳🥳!!!",
description: "You now have permissions to perform this action.",
type: "success",
duration: 3000,
})
}
return (
<HStack>
<Button variant="outline" size="sm" onClick={show}>
Show Toast
</Button>
<Button variant="outline" size="sm" onClick={update}>
Update Toast
</Button>
</HStack>
)
}
自定义时长
¥Custom Duration
使用 duration 属性设置提示框的持续时间。
¥Use the duration prop to set the duration of the toast.
"use client"
import { Button } from "@chakra-ui/react"
import { toaster } from "@/components/ui/toaster"
const Demo = () => {
return (
<Button
variant="outline"
size="sm"
onClick={() =>
toaster.create({
description: "File saved successfully",
duration: 6000,
})
}
>
Show Toast
</Button>
)
}
暂停和播放
¥Pause and Play
使用 toaster 对象上的 pause 和 resume 方法暂停和播放提示框。
¥Use the pause and resume methods on the toaster object to pause and play
the toast.
暂停 Toast 消息可防止其超时,而恢复 Toast 消息将使用剩余时长重新启用超时。
¥Pausing a toast prevents it from timing out, while resuming it will reenable the timeout using the remaining duration.
"use client"
import { Button, HStack } from "@chakra-ui/react"
import { toaster } from "@/components/ui/toaster"
import { useId, useState } from "react"
import { HiPause, HiPlay } from "react-icons/hi"
const Demo = () => {
const id = useId()
const [paused, setPaused] = useState(false)
const [shown, setShown] = useState(false)
const show = () => {
toaster.success({
id,
title: "This is a success toast",
onStatusChange: (details) => {
if (details.status === "visible") {
setShown(true)
} else if (details.status === "dismissing") {
setShown(false)
}
},
})
}
const pause = () => {
toaster.pause(id)
setPaused(true)
}
const play = () => {
toaster.resume(id)
setPaused(false)
}
return (
<HStack>
<Button variant="outline" size="sm" onClick={show} disabled={shown}>
Show Toast
</Button>
<Button
variant="outline"
size="sm"
onClick={pause}
disabled={!shown || paused}
>
<HiPause />
Pause Toast
</Button>
<Button
variant="outline"
size="sm"
onClick={play}
disabled={!shown || !paused}
>
<HiPlay />
Play Toast
</Button>
</HStack>
)
}
生命周期
¥Lifecycle
使用 toaster 函数上的 onStatusChange 属性来监听提示框状态的变化。
¥Use the onStatusChange prop on the toaster function to listen for changes to
the toast's status.
"use client"
import { Button, HStack, Stack, Text } from "@chakra-ui/react"
import { toaster } from "@/components/ui/toaster"
import { useState } from "react"
const Demo = () => {
const [statusLog, setStatusLog] = useState<[number, string][]>([])
const [dismissed, setDismissed] = useState(true)
return (
<Stack align="flex-start">
<Button
disabled={!dismissed}
variant="outline"
size="sm"
onClick={() =>
toaster.create({
description: "This is a toast",
type: "info",
onStatusChange({ status }) {
setDismissed(status === "unmounted")
setStatusLog((prev) => [[Date.now(), status], ...prev])
},
})
}
>
Show Toast
</Button>
<Stack padding="2" width="full" role="log" borderWidth="1px" minH="100px">
{statusLog.map(([time, toastStatus], i) => {
const date = new Date(time)
return (
<HStack as="pre" fontFamily="mono" textStyle="sm" key={i}>
{date.toLocaleTimeString()}{" "}
<Text fontWeight="bold">{toastStatus}</Text>
</HStack>
)
})}
</Stack>
</Stack>
)
}
最大可见 Toast 数量
¥Maximum Visible Toasts
在 createToaster 函数上设置 max 属性以定义可同时渲染的最大 toast 数量。当 Toast 被关闭时,任何额外的 Toast 都会被排队渲染。
¥Set the max prop on the createToaster function to define the maximum number
of toasts that can be rendered at any one time. Any extra toasts will be queued
and rendered when a toast has been dismissed.
@/components/ui/toaster.tsx
const toaster = createToaster({
max: 3,
})放置位置
¥Placement
Toast 可以显示在页面的四个角落。我们建议你选择一个所需的位置并在 createToaster 函数中进行配置。
¥Toasts can be displayed on all four corners of a page. We recommend picking one
desired position and configure it in the createToaster function.
@/components/ui/toaster.tsx
const toaster = createToaster({
placement: "top-end",
})重叠提示框
¥Overlapping Toasts
默认情况下,提示框会堆叠在一起。要使提示框相互重叠,请在 createToaster 函数中将 overlap 属性设置为 true。
¥By default, toasts are stacked on top of each other. To make the toasts overlap
each other, set the overlap prop to true in the createToaster function.
@/components/ui/toaster.tsx
const toaster = createToaster({
placement: "top-end",
overlap: true,
})页面空闲行为
¥Page Idle Behavior
页面空闲/隐藏时暂停 Toast 计时器。
¥Pause toast timers when the page is idle/hidden.
@/components/ui/toaster.tsx
const toaster = createToaster({
pauseOnPageIdle: true,
})偏移
¥Offset
在 createToaster 函数中设置 offsets 属性,以使提示框偏离屏幕边缘。
¥Set the offsets prop in the createToaster function to offset the toasts from
the edges of the screen.
@/components/ui/toaster.tsx
const toaster = createToaster({
offsets: "20px",
})或者,你可以使用 offsets 属性设置屏幕每个边缘的偏移量。
¥Alternatively, you can use the offsets prop to set the offset for each edge of
the screen.
@/components/ui/toaster.tsx
const toaster = createToaster({
offsets: { left: "20px", top: "20px", right: "20px", bottom: "20px" },
})属性
¥Props
烤面包机
¥Toaster
根元素
¥Root
| Prop | Default | Type |
|---|---|---|
as | React.ElementTypeThe underlying element to render. | |
asChild | booleanUse the provided child element as the default rendered element, combining their props and behavior. For more details, read our Composition guide. | |
unstyled | booleanWhether to remove the component's style. |
标题
¥Title
| Prop | Default | Type |
|---|---|---|
as | React.ElementTypeThe underlying element to render. | |
asChild | booleanUse the provided child element as the default rendered element, combining their props and behavior. For more details, read our Composition guide. |
描述
¥Description
| Prop | Default | Type |
|---|---|---|
as | React.ElementTypeThe underlying element to render. | |
asChild | booleanUse the provided child element as the default rendered element, combining their props and behavior. For more details, read our Composition guide. |
ActionTrigger
| Prop | Default | Type |
|---|---|---|
as | React.ElementTypeThe underlying element to render. | |
asChild | booleanUse the provided child element as the default rendered element, combining their props and behavior. For more details, read our Composition guide. |
CloseTrigger
| Prop | Default | Type |
|---|---|---|
as | React.ElementTypeThe underlying element to render. | |
asChild | booleanUse the provided child element as the default rendered element, combining their props and behavior. For more details, read our Composition guide. |