如何在Material UI的TextField组件末尾追加按钮?

你之前的代码效果不美观,是因为默认InputAdornment的内边距会让按钮内嵌在输入框内部,没有和输入框边框对齐贴合,通过简单的样式调整即可实现目标效果:
方案1:基于endAdornment调整
修改输入框和按钮的样式,移除多余内边距,调整圆角即可:
<TextField fullWidth variant="outlined" label="Add Something" InputProps={{ endAdornment: ( <InputAdornment position="end"> <Button aria-label="Add" edge="end" color="primary" variant="contained" sx={{ borderTopLeftRadius: 0, borderBottomLeftRadius: 0, height: "56px", // 和outlined尺寸的TextField高度对齐 mr: "-14px" // 抵消InputAdornment默认右间距 }} > ADD </Button> </InputAdornment> ), sx: { paddingRight: 0 // 移除输入框右侧默认内边距 } }} />
方案2:布局组件拼接
如果需要更灵活的适配不同尺寸、不同类型的输入框和按钮,可以直接用布局组件拼接两个元素,耦合度更低:
<Stack direction="row" spacing={0} fullWidth> <TextField variant="outlined" label="Add Something" sx={{ flex: 1, "& .MuiOutlinedInput-root": { borderTopRightRadius: 0, borderBottomRightRadius: 0 } }} /> <Button variant="contained" color="primary" sx={{ height: "56px", borderTopLeftRadius: 0, borderBottomLeftRadius: 0 }} > ADD </Button> </Stack>
内容的提问来源于stack exchange,提问作者N N
相关产品推荐
相关产品推荐

