【发布时间】:2020-09-27 16:07:34
【问题描述】:
如何使 textarea 成为灵活的组件:
- width = defaultMaxWidth,但不超过 parant 大小的 100%。
- 可编辑,所以我可以手动更改它的大小。
这是我的沙箱attempt(你可以编辑它),但它有两个问题:
- 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%;
`;
【问题讨论】:
标签: html css styled-components