【问题标题】:How to dynamically adjust textarea height with React?如何使用 React 动态调整文本区域的高度?
【发布时间】:2019-02-28 01:42:18
【问题描述】:

我想用 Refs 动态调整我的 textarea 高度并将其传递给 state,但它不能正常工作。

我创建了一个代码框来帮助您了解我到底想要什么。

https://codesandbox.io/s/ol5277rr25

【问题讨论】:

  • 你到底想要什么?您能否编辑您的问题以用简单的英文文本更好地解释它?
  • 这很简单,我希望我的文本区域的高度根据文本进行调整。

标签: css reactjs textarea


【解决方案1】:

这是一个不涉及 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 也将处理删除。
【解决方案2】:

你可以通过使用 react 的 useRefuseLayoutEffect 内置钩子来解决这个问题。这种方法会在浏览器中进行任何渲染之前更新文本区域的高度,从而避免文本区域的任何“视觉更新”/闪烁/跳跃。

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://codesandbox.io/s/react-textarea-auto-height-s96b2

【讨论】:

    【解决方案3】:

    您可以检查回购。或者您可以将包添加到您的项目中。

    https://github.com/andreypopp/react-textarea-autosize

    如果你真的愿意了解逻辑是如何工作的;

    https://github.com/andreypopp/react-textarea-autosize/blob/master/src/calculateNodeHeight.js

    有一个源代码,所有的计算都在一起。

    【讨论】:

    • 谢谢我已经使用了 react-textarea-autosize 和 react-autosize-textarea 但在我的情况下,我真的想自己调整 textarea 的高度,带有参考和状态
    • 这就是我分享源代码的原因。我可以编写你的代码,但你不会理解阅读开源代码。首先你可能会有点困惑。在一些帮助下,鼓励你是我的事。从逻辑上去理解和写代码也是你的事。
    • 我试过了,但我想要一个简单的解决方案。不要像那样复杂。我确信 Refs 和 State 有一个更简单的解决方案可以做到这一点。我用基本逻辑做了一个codesandbox,它工作但不正确,我觉得有一点让我无法理解..codesandbox.io/s/ol5277rr25
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-21
    • 1970-01-01
    • 1970-01-01
    • 2017-01-17
    • 2011-08-04
    • 1970-01-01
    相关资源
    最近更新 更多