我一直在尝试调整material-ui的<TextField>
的大小适合动态容器的组件。然而,这样做会导致光标输入被允许完全离开文本区域(参见下面的图像#2/#3)。此外,当没有输入文本时,光标开始于相对于其容器高度的居中位置(参见下面的图像#1)。
以下是实际操作的基本示例。
const TextArea = () =>
{
const containerStyle = {
width: 200,
height: 200
}
const textFieldStyle = {
marginTop: 8,
width: '100%',
height: 'calc(100% - 8px)'
}
const inputStyle = {
width: '100%',
height: '100%',
overflowY: 'auto' // tried this afterwards to no avail
}
const props = {
style: textFieldStyle,
label: 'Workings',
multiline: true,
variant: 'outlined',
InputProps: {style: inputStyle}
}
return (
<div style={containerStyle}>
<TextField {...props}/>
</div>
);
}
我想知道如何调整大小<TextField>
填充容器,同时保留其预期功能。
编辑:我正在使用@material-ui/core v3.6.0
和react v16.4.1
编辑: Here is a CodeSandbox显示问题。
最佳答案
主要问题是您没有指定 rows
属性。
rows Number of rows to display when multiline option is set to true (docs).
多行 TextField 的默认行为是从一行开始并根据需要增长(从而最终增长到容器高度的范围之外)。您可以指定 maxRows
来限制此自动增长行为,也可以通过指定 来固定行数(如果您尝试输入更多行,则会出现滚动条) rows
属性。
您可以尝试根据容器高度计算行
的值:
const props = {
style: textFieldStyle,
label: "derive rows from height",
multiline: true,
variant: "outlined",
rows: containerStyle.height / 21,
InputProps: { style: inputStyle }
};
我不保证数学对于不同大小的稳健性,但除以 21 似乎在这种情况下有效。
另一种方法是删除显式高度并允许 TextField
上的 rows
属性控制所有其他高度:
const props = {
style: textFieldStyle, // style would not control height
label: "no explicit height",
multiline: true,
variant: "outlined",
rows: 9,
InputProps: { style: inputStyle } // style would not control height
};
当您提到想要填充动态容器的高度时,我不确定是什么驱动了动态性质,但如果可能的话,我会避免动态更改容器的高度,而是动态更改上的行数文本区域(即使用第二种方法)。
这是一个显示这两种方法的沙箱:
关于javascript - 调整 Material-UI <TextField> 大小会导致光标退出其容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54366564/