显示
用于根据条件有条件地渲染视图的一部分。
"use client"
import { Button, Show, Stack } from "@chakra-ui/react"
import { useState } from "react"
const Demo = () => {
const [count, setCount] = useState(0)
return (
<Stack align="flex-start">
<Button variant="outline" onClick={() => setCount(count + 1)}>
Value: {count}
</Button>
<Show when={count > 3}>
<div>My Content</div>
</Show>
</Stack>
)
}
用法
该当 when
值为真时,Show
组件会渲染其子级,否则会渲染 fallback
属性。
import { Show } from "@chakra-ui/react"
<Show when={...} fallback={...}>
<div>Content</div>
</Show>
示例
回退
当数组为空或未定义时,使用 fallback
属性渲染回退组件。
尚未到达。请继续点击...
"use client"
import { Button, Show, Stack, Text } from "@chakra-ui/react"
import { useState } from "react"
const Demo = () => {
const [count, setCount] = useState(0)
return (
<Stack align="flex-start">
<Button variant="outline" onClick={() => setCount(count + 1)}>
Value: {count}
</Button>
<Show
when={count > 3}
fallback={<Text>Not there yet. Keep clicking...</Text>}
>
<div>Congrats! I am here</div>
</Show>
</Stack>
)
}
渲染 Prop
使用 children
渲染 Prop 来缩小 when
值的类型,并移除 undefined
| null
。
值10
import { Show } from "@chakra-ui/react"
const Demo = () => {
const value: number | undefined = 10
return <Show when={value}>{(value) => <div>Value: {value}</div>}</Show>
}
属性
属性 | 默认 | 类型 |
---|---|---|
when | T | null | undefined 如果为 `true`,它将渲染 `children` 属性 | |
fallback | React.ReactNode 如果 `when` 为 `false`,则渲染的回退内容 |