开发环境
・反应
・打字稿
・ next.js
・样式组件
带有自动换行符的文本区域
最大高度设置为100px。
但是,背景div标签的大小最大为100px,但是只有textarea超过100px。
我更改了高度:$ {({textArea)=> texth} px;到$ {({texth}:TArea)=>(texth <= 90?texth:90)} px;但是,高度已从初始值变为90px。
TextArea.tsx
import React, { FunctionComponent, useEffect, useRef, useState } from 'react';
import styled from 'styled-components';
type TArea = {
parent: number;
texth: number;
};
const TextAreaA = styled.div<TArea>`
padding: 12px 12px;
height: 25px;
background: #e1e6ed;
border-radius: 24px;
min-height: ${({ parent }: TArea) => (parent <= 100 ? parent : 100)}px;
textarea {
margin-left: 10px;
margin-bottom: 1px;
width: calc(100% - 39px);
font-size: 14px;
resize: none;
height: ${({texth }: TArea) => (texth <= 100 ? texth : 100)}px;
::-webkit-resizer {
display: none;
}
}
`;
type Props = {
text: string;
placeholder: string;
onHandleChange?: (e:React.ChangeEvent<HTMLTextAreaElement>) => void;
};
export const TextArea: FunctionComponent<Props> = ({
text,
placeholder,
onHandleChange,
}) => {
const textAreaRef = useRef<HTMLTextAreaElement>(null);
const [textAreaHeight, setTextAreaHeight] = useState('auto');
const [parentHeight, setParentHeight] = useState('auto');
useEffect(() => {
setParentHeight(`${textAreaRef.current!.scrollHeight}`);
setTextAreaHeight(`${textAreaRef.current!.scrollHeight}`);
}, [text]);
const onChangeHandler = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
setTextAreaHeight('auto');
console.log(textAreaHeight);
console.log(parentHeight);
setParentHeight(`${textAreaRef.current!.scrollHeight}`);
onHandleChange(e);
};
return (
<TextAreaA
parent={Number(parentHeight)}
texth={Number(texth)}
>
<textarea
placeholder={placeholder}
ref={textAreaRef}
rows={1}
onChange={onChangeHandler}
value={text}
/>
</TextAreaA>
);
};