981377660LMT / ts

ts学习
6 stars 1 forks source link

textArea 自动调节高度(不是自动换行) #434

Open 981377660LMT opened 7 months ago

981377660LMT commented 7 months ago

使用隐藏的div

  const textAreaRef = useRef<HTMLTextAreaElement>(null);
  const hiddenDivRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const textArea = textAreaRef.current;
    const hiddenDiv = hiddenDivRef.current;
    if (textArea && hiddenDiv) {
      if (textArea.value.length === 0) {
        setValue(' ');
        return;
      }
      hiddenDiv.textContent = textArea.value;
      hiddenDiv.style.width = `${textArea.offsetWidth}px`;
      const { fontSize, lineHeight } = window.getComputedStyle(textArea);
      hiddenDiv.style.fontSize = fontSize;
      hiddenDiv.style.lineHeight = lineHeight;
      hiddenDiv.style.whiteSpace = 'pre-wrap';
      hiddenDiv.style.overflowWrap = 'break-word';
      textArea.style.height = `${hiddenDiv.clientHeight}px`;
    }
  }, [textAreaRef?.current?.value]);

 <textarea
    ref={textAreaRef}
    className="xtable-number-textarea"
    style={{
      width: props.style.width - 2 * INIT_X
    }}
    value={value}
    onBlur={() => {
      submit(value);
    }}
    onKeyDown={handleKeyDown}
    onChange={handleInputChange}
    placeholder={props.placeholder}
  />
  <div ref={hiddenDivRef} style={{ visibility: 'hidden', position: 'absolute', top: 0 }} />
</>

getComputedStyle 是一个浏览器提供的方法,用于获取一个元素最终应用的所有 CSS 属性值。这些值是在所有相关的 CSS 样式和 CSS 规则应用后得到的。

981377660LMT commented 7 months ago

去除 textArea 样式

如果你想要去除 textarea 的默认样式,你可以使用 CSS 来实现。以下是一个基本的例子:

textarea {
  outline: none;
  border: none;
  background: none;
  resize: none;
}

这段 CSS 代码将移除 textarea 的轮廓(outline)、边框(border)、背景(background)以及禁止用户调整大小(resize)。你可以根据需要添加或删除属性。