Chakra UI卡片中Stack Divider不显示问题求助
问题分析与解决方法
你的Stack Divider无法显示,核心原因是每个<Stack>组件内仅包含一个子元素——Chakra UI的StackDivider是用来分隔Stack的多个子组件的,只有当Stack包含2个及以上子元素时,分隔线才会被渲染。
看你的代码结构:在results.items.map循环中,每个搜索结果都单独套了一层<CardBody>,内部的<Stack>只包裹了一个<Box>,这种情况下每个Stack都只有一个子元素,自然看不到分隔线。
针对不同需求的修改方案
需求1:在不同搜索结果之间显示分隔线
把<Stack>提到循环外层,让所有搜索结果作为Stack的子元素,同时统一用一个<CardBody>包裹整个Stack:
<Card width={"100%"} borderWidth="1px" borderRadius="lg" marginX="auto" paddingX={3} maxWidth="3xl"> <CardHeader color="blue.500" size={"sm"} mt={3}> Citations {results.searchInformation.formattedTotalResults} <Divider orientation="horizontal" /> </CardHeader> <CardBody maxWidth="3xl"> {/* 将Stack移到循环外层,所有搜索结果作为Stack的子元素 */} <Stack divider={<StackDivider />} spacing='2'> {results.items.map((result) => ( <Box key={result.link}> <Link color='blue.500' href={result.link} isExternal> {result.displayLink}<ExternalLinkIcon mx='4px' /> </Link> <Link href={result.link}> <Heading as='h2' size={'md'}>{result.title}</Heading> </Link> <Text noOfLines={3}> {Parser(result.htmlSnippet)} </Text> </Box> ))} </Stack> </CardBody> </Card>
需求2:在单个搜索结果内部的元素之间显示分隔线
把单个<Box>拆成多个子元素直接放到Stack中,让Stack拥有多个子元素,分隔线就会渲染在这些元素之间:
<Card width={"100%"} borderWidth="1px" borderRadius="lg" marginX="auto" paddingX={3} maxWidth="3xl"> <CardHeader color="blue.500" size={"sm"} mt={3}> Citations {results.searchInformation.formattedTotalResults} <Divider orientation="horizontal" /> </CardHeader> {results.items.map((result) => ( <CardBody key={result.link} maxWidth="3xl"> {/* Stack内部包含多个独立子元素,分隔线自动渲染 */} <Stack divider={<StackDivider />} spacing='2'> <Link color='blue.500' href={result.link} isExternal> {result.displayLink}<ExternalLinkIcon mx='4px' /> </Link> <Link href={result.link}> <Heading as='h2' size={'md'}>{result.title}</Heading> </Link> <Text noOfLines={3}> {Parser(result.htmlSnippet)} </Text> </Stack> </CardBody> ))} </Card>
补充说明
不需要额外给StackDivider指定宽度,它默认会继承Stack的宽度,只要满足「Stack包含2个及以上子元素」这个前提,就能正常显示。
内容的提问来源于stack exchange,提问作者Enrico Shippole
相关产品推荐
相关产品推荐

