首页 > 解决方案 > 具有默认宽度的灵活 textarea 组件

问题描述

如何使 textarea 成为灵活的组件:

  1. 宽度 = defaultMaxWidth,但不超过参数大小的 100%。
  2. 可编辑,所以我可以手动更改它的大小。

这是我的沙盒尝试(您可以编辑它),但它有两个问题:

  1. 尝试拉伸时,Textarea 的大小受 defaultMaxWidth 限制。
  2. 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%;
`;

标签: htmlcssstyled-components

解决方案


要修复边距,我需要设置 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%;
`;

推荐阅读