One
Two
Three
import { For } from "@chakra-ui/react"
const Demo = () => {
return (
<For each={["One", "Two", "Three"]}>
{(item, index) => <div key={index}>{item}</div>}
</For>
)
}
用法
¥Usage
For
组件用于以强类型方式渲染项目列表。它与 .map()
类似。
¥The For
component is used to render a list of items in a strongly typed
manner. It is similar to the .map()
.
import { For } from "@chakra-ui/react"
<For each={[]} fallback={...} />
示例
¥Examples
对象
¥Object
以下是使用 For
组件循环遍历对象的示例。
¥Here's an example of using the For
component to loop over an object.
Naruto
Powers: Shadow Clone, Rasengan
Sasuke
Powers: Chidori, Sharingan
Sakura
Powers: Healing, Super Strength
import { Box, For, Stack, Text } from "@chakra-ui/react"
const Demo = () => {
return (
<Stack>
<For
each={[
{ name: "Naruto", powers: ["Shadow Clone", "Rasengan"] },
{ name: "Sasuke", powers: ["Chidori", "Sharingan"] },
{ name: "Sakura", powers: ["Healing", "Super Strength"] },
]}
>
{(item, index) => (
<Box borderWidth="1px" key={index} p="4">
<Text fontWeight="bold">{item.name}</Text>
<Text color="fg.muted">Powers: {item.powers.join(", ")}</Text>
</Box>
)}
</For>
</Stack>
)
}
回退
¥Fallback
当数组为空或未定义时,使用 fallback
属性渲染备用组件。
¥Use the fallback
prop to render a fallback component when the array is empty
or undefined.
No items to show
import { For, Stack, VStack } from "@chakra-ui/react"
import { DecorativeBox } from "compositions/lib/decorative-box"
import { LuBox } from "react-icons/lu"
const Demo = () => {
return (
<Stack gap="4">
<For
each={[]}
fallback={
<VStack textAlign="center" fontWeight="medium">
<LuBox />
No items to show
</VStack>
}
>
{(item, index) => (
<DecorativeBox h="10" key={index}>
{item}
</DecorativeBox>
)}
</For>
</Stack>
)
}
属性
¥Props
Prop | Default | Type |
---|---|---|
each | T[] | readonly T[] | undefined The array to iterate over | |
fallback | React.ReactNode | undefined The fallback content to render when the array is empty |