html - 具有默认宽度的灵活 textarea 组件
问题描述
如何使 textarea 成为灵活的组件:
- 宽度 = defaultMaxWidth,但不超过参数大小的 100%。
- 可编辑,所以我可以手动更改它的大小。
这是我的沙盒尝试(您可以编辑它),但它有两个问题:
- 尝试拉伸时,Textarea 的大小受 defaultMaxWidth 限制。
- Textarea 有边距问题
代码:
import React, { forwardRef } from "react";
import styled from "styled-components";
const Textarea = forwardRef((props, ref) => {
return (
<Wrapper {...props}>
<StyledTextarea ref={ref} {...props} />
</Wrapper>
);
});
export default function App() {
return (
<Centered>
<Textarea
height="300px"
defaultMaxWidth="300px"
placeholder="can't stretch"
/>
<Textarea
height="300px"
defaultMaxWidth="3000px"
placeholder="textarea is in parent size, but there is problems with my right margins!"
/>
</Centered>
);
}
const Centered = styled.div`
display: flex;
flex-direction: column;
align-items: center;
`;
const defPadding = 5;
const defMargin = 5;
const StyledTextarea = styled.textarea`
margin: ${defMargin}px;
border-radius: 5px;
outline: none;
max-width: calc(
${p => p.defaultMaxWidth || "100%"} - ${defPadding * 2 + defMargin * 2}px
);
width: 100%;
height: ${p => p.height || "100px"};
`;
const Wrapper = styled.div`
max-width: calc(
${p => p.defaultMaxWidth || "100%"} - ${defPadding * 2 + defMargin * 2}px
);
width: 100%;
`;
解决方案
要修复边距,我需要设置 textarea max-width = 100% - padding * 2 + margin * 2。
为了使其灵活,您需要按原样使用宽度。
这是解决方案(沙箱更新):
import React, { forwardRef } from "react";
import styled from "styled-components";
const Textarea = forwardRef((props, ref) => {
return (
<Wrapper {...props}>
<StyledTextarea ref={ref} {...props} />
</Wrapper>
);
});
export default function App() {
return (
<Centered>
<Textarea height="300px" width="300px" placeholder="can't stretch" />
<Textarea
height="300px"
width="3000px"
placeholder="textarea is in parent size, but there is problems with my right margins!"
/>
</Centered>
);
}
const Centered = styled.div`
width: 100%;
`;
const defPadding = 5;
const defMargin = 5;
const StyledTextarea = styled.textarea`
margin: ${defMargin}px;
border-radius: 5px;
outline: none;
max-width: calc(
${p => p.defaultMaxWidth || "100%"} - ${defPadding * 2 + defMargin * 2}px
);
width: ${({ width }) => width || "400px"};
max-width: calc(100% - ${defPadding * 4}px);
`;
const Wrapper = styled.div`
width: 100%;
`;
推荐阅读
- python - 如何在成功时将内容添加到气流发送的电子邮件中
- python - 以字典格式读取和解析逻辑
- azure-devops - 如何在 Azure 管道中使用“公共项目的无限分钟和并行作业”
- python - 确定代码是在本地运行还是部署到 PythonAnywhere 的可靠方法是什么?
- python - 在 Python 程序中删除列值高于常量的 Panda 行
- scala - 如何存储文本文件中的变量并操作其内容:Spark RDD / Scala -
- javascript - 如果 column type=1 显示标签文本 Active else display Not active,如何检查 component.html?
- javafx - 如何设置一个 KeyListener 来监听 JavaFX 中的 Windows 键,而不需要操作系统使用该按键作为操作?
- reactjs - 在 react native 中导航时如何从另一个组件调用函数?
- docker - 私有托管代理 (Azure DevOps) 上的 Docker 构建失败