【发布时间】:2019-02-28 01:42:18
【问题描述】:
我想用 Refs 动态调整我的 textarea 高度并将其传递给 state,但它不能正常工作。
我创建了一个代码框来帮助您了解我到底想要什么。
【问题讨论】:
-
你到底想要什么?您能否编辑您的问题以用简单的英文文本更好地解释它?
-
这很简单,我希望我的文本区域的高度根据文本进行调整。
我想用 Refs 动态调整我的 textarea 高度并将其传递给 state,但它不能正常工作。
我创建了一个代码框来帮助您了解我到底想要什么。
【问题讨论】:
这是一个不涉及 refs 的简单解决方案。 textarea 使用一些 CSS 和 rows 属性动态调整。我最近自己用过这个(例如:https://codesandbox.io/embed/q8174ky809)。
在你的组件中,抓取textarea,计算当前行数,加1:
const textArea = document.querySelector('textarea')
const textRowCount = textArea ? textArea.value.split("\n").length : 0
const rows = textRowCount + 1
return (
<div>
<textarea
rows={rows}
placeholder="Enter text here."
onKeyPress={/* do something that results in rendering */}
... />
</div>
)
在你的 CSS 中:
textarea {
min-height: 26vh; // adjust this as you see fit
height: unset; // so the height of the textarea isn't overruled by something else
}
【讨论】:
onKeyDown 而不是 onKeyPress 也将处理删除。
你可以通过使用 react 的 useRef 和 useLayoutEffect 内置钩子来解决这个问题。这种方法会在浏览器中进行任何渲染之前更新文本区域的高度,从而避免文本区域的任何“视觉更新”/闪烁/跳跃。
import React from "react";
const MIN_TEXTAREA_HEIGHT = 32;
export default function App() {
const textareaRef = React.useRef(null);
const [value, setValue] = React.useState("");
const onChange = (event) => setValue(event.target.value);
React.useLayoutEffect(() => {
// Reset height - important to shrink on delete
textareaRef.current.style.height = "inherit";
// Set height
textareaRef.current.style.height = `${Math.max(
textareaRef.current.scrollHeight,
MIN_TEXTAREA_HEIGHT
)}px`;
}, [value]);
return (
<textarea
onChange={onChange}
ref={textareaRef}
style={{
minHeight: MIN_TEXTAREA_HEIGHT,
resize: "none"
}}
value={value}
/>
);
}
【讨论】:
您可以检查回购。或者您可以将包添加到您的项目中。
https://github.com/andreypopp/react-textarea-autosize
如果你真的愿意了解逻辑是如何工作的;
https://github.com/andreypopp/react-textarea-autosize/blob/master/src/calculateNodeHeight.js
有一个源代码,所有的计算都在一起。
【讨论】: