跳到主要内容

react-textarea

2023年11月08日
柏拉文
越努力,越幸运

一、高度自适应


import { useState } from 'react';

function App() {
const [value, setValue] = useState<string>('');

const handleTextareaChange = (e: any) => {
const style = getComputedStyle(e.target);
const lineHeight = parseInt(style.lineHeight.slice(0, -2), 10);
let height = parseInt(style.height.slice(0, -2), 10);

if (e.target.scrollHeight > height) {
e.target.style.height = `${e.target.scrollHeight + 2}px`;
} else {
while (height >= e.target.scrollHeight) {
e.target.style.height = `${height - lineHeight}px`;
height -= lineHeight;
}
e.target.style.height = `${height + lineHeight}px`;
}

setValue(e.target.value);
};

return (
<div>
<textarea
value={value}
onChange={handleTextareaChange}
style={{
resize: 'none',
height: '36px',
lineHeight: '20px',
boxSizing: 'border-box'
}}
></textarea>
</div>
);
}

export default App;