You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React+Chakra UI开发视频聊天界面:maxHeight属性失效求助

解决React + Chakra UI中视频元素忽略高度限制的问题

问题分析

核心问题是HTML video元素默认会维持自身原始宽高比:当仅给父Flex容器设置maxHeight时,video不会自动继承容器的高度限制——它会优先保证视频比例,导致高度超出容器范围。而maxWidth生效是因为浏览器限制宽度时,会自动按比例缩放高度,但反向限制高度不会触发同样的行为。你看到的紫色虚线是Chrome标记的元素溢出容器区域,因为Flex容器默认overflow: visible,超出部分会显示在容器外。

解决方案

要让视频遵守容器高度限制,需要从约束视频尺寸、保留宽高比、调整容器布局规则三个方面入手:

方案1:用Chakra组件包裹video并设置约束

给video套一层Box,通过maxHeight、width和object-fit控制显示:

import { Box } from "@chakra-ui/react";

export function LocalVideoElement() {
    const streamInfo = GetStreamInfo();
    const [localVideoElement, setLocalVideoElement] = useState<HTMLVideoElement | null>(null);

    useEffect(() => {
        if (localVideoElement && streamInfo.localStream) {
            localVideoElement.srcObject = streamInfo.localStream;
        }
    }, [localVideoElement, streamInfo.localStream]);

    return (
        <Box maxHeight="100%" width="auto">
            <video
                id='localVideo'
                ref={(video) => setLocalVideoElement(video)}
                controls={false}
                autoPlay
                playsInline
                muted
                style={{
                    maxHeight: "100%",
                    width: "auto",
                    objectFit: "contain" // 保持视频比例,避免拉伸
                }}
            />
        </Box>
    );
}

同时调整父容器,明确高度并处理溢出:

export default function VideoChatFlex() {
    return (
        <Flex 
            id='videoContainer' 
            direction='column' 
            align='center' 
            justify='center' 
            height="100px" // 明确容器高度,替代或配合maxHeight
            overflow="hidden" // 隐藏溢出部分,消除紫色虚线
            gap="4" // 可选:给两个视频添加间距
        >
            <LocalVideoElement />
            <RemoteVideoElement />
        </Flex>
    );
}

方案2:直接给video元素设置Chakra样式

如果不想额外嵌套组件,可直接用__css属性给video添加样式:

return (
    <video
        id='localVideo'
        ref={(video) => setLocalVideoElement(video)}
        controls={false}
        autoPlay
        playsInline
        muted
        __css={{
            maxHeight: "100%",
            width: "auto",
            objectFit: "contain"
        }}
    />
);

关键细节

  • object-fit: contain:确保视频在指定尺寸内保持原始比例,不会拉伸;若需要填充容器可改用cover(会裁剪部分视频)。
  • 父容器需设置明确高度(height或minHeight),仅maxHeight无法让子元素正确感知可用空间。
  • maxHeight: 100%让video继承父容器高度限制,width: auto自动按比例缩放宽度。

内容的提问来源于stack exchange,提问作者nlouis56

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 21:30:13