展示
用于根据条件有条件地渲染部分视图。
"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>
)
}
用法
¥Usage
当 when 值为真时,Show 组件渲染其子组件,否则渲染 fallback 属性。
¥The Show component renders its children when the when value is truthy,
otherwise it renders the fallback prop.
import { Show } from "@chakra-ui/react"
<Show when={...} fallback={...}>
<div>Content</div>
</Show>
示例
¥Examples
回退
¥Fallback
当数组为空或未定义时,使用 fallback 属性渲染备用组件。
¥Use the fallback prop to render a fallback component when the array is empty
or undefined.
Not there yet. Keep clicking...
"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>
)
}
渲染属性
¥Render Prop
使用 children 渲染属性缩小 when 值的类型并移除 undefined | null
¥Use the children render prop to narrow the type of the when value and remove
undefined | null
Value: 10
import { Show } from "@chakra-ui/react"
const Demo = () => {
const value: number | undefined = 10
return <Show when={value}>{(value) => <div>Value: {value}</div>}</Show>
}
属性
¥Props
| Prop | Default | Type |
|---|---|---|
when | T | null | undefinedIf `true`, it'll render the `children` prop | |
fallback | React.ReactNode | undefinedThe fallback content to render if `when` is `false` | |
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. |