如何让Material UI TableCell组件的子元素填充满单元格高度?
解决方案
核心思路是不破坏表格原生布局规则,通过绝对定位让TextField完全填充父级TableCell的可视区域:
- 给所有包含TextField的
TableCell添加position: relative样式,作为定位父级 - 给
TextField添加绝对定位样式四边对齐父级TableCell,同时适配内部textarea高度占满容器
修改后完整代码如下:
import React from "react"; // MUI v5导入路径为@mui/material,若仍使用v4版本可保留原@material-ui/core导入 import * as material from "@mui/material"; const App = () => ( <material.TableContainer component={material.Paper}> <material.Table aria-label="simple table" stickyHeader={true} size="small"> <material.TableBody> <material.TableRow> <material.TableCell align="center" style={{ backgroundColor: "red", padding: 0, position: "relative" // 新增:作为定位父级 }} > <material.TextField multiline variant="outlined" InputProps={{ sx: { // 适配内部输入容器和文本域高度占满 height: "100%", "& textarea": { height: "100% !important" } } }} style={{ position: "absolute", // 新增:绝对定位铺满父容器 top: 0, left: 0, right: 0, bottom: 0, backgroundColor: "yellow" }} /> </material.TableCell> <material.TableCell align="center" style={{ backgroundColor: "red", padding: 0, position: "relative" // 新增:作为定位父级 }} > <material.TextField multiline variant="outlined" InputProps={{ sx: { height: "100%", "& textarea": { height: "100% !important" } } }} style={{ position: "absolute", top: 0, left: 0, right: 0, bottom: 0, backgroundColor: "yellow" }} /> </material.TableCell> </material.TableRow> </material.TableBody> </material.Table> </material.TableContainer> ); export default App;
该方案完全保留表格原生布局特性,行高由内容更高的那列TextField自动撑开,另一列TextField会始终填满整个TableCell,不会露出单元格背景。
内容的提问来源于stack exchange,提问作者codego
相关产品推荐
相关产品推荐

