【问题标题】:Change scrollHeight of other component更改其他组件的滚动高度
【发布时间】:2022-01-01 20:16:09
【问题描述】:

我有这样的组件:

const Panel = () => {
  const input = useRef<HTMLTextAreaElement>(null);

  return (
    <Wrapper>
      <Input
        ref={input}
      />
        <Button
          onClick={() => {
            input.current?.scrollHeight = "";
          }}
        >
        </Button>
    </Wrapper>
  );
};

我需要在单击按钮时更改输入的scrollHeight,所以我尝试使用useRef,但出现错误:Cannot assign to 'scrollHeight' because it is a read-only property。我该如何解决?

【问题讨论】:

  • 您是否尝试过调整内容样式的高度或宽度?
  • 我怎样才能调整按钮组件的输入样式?

标签: javascript html reactjs typescript components


【解决方案1】:

从你所写的内容来看,我没有太多可做的,但这样的事情可能会有所帮助:

const Panel = () => {
  const input = useRef<HTMLTextAreaElement>(null);
   // collect the current style height that is used to establish the scroll height
  const height = document.getElementyById()?.clientHeight

  return (
    <Wrapper>
      <Input
        ref={input}
      />
        <Button
          onClick={() => {
             function (){
                document.getElementById()?.style.height = `${height}px`;
              }} 
        > // add to the height this way, start with the clientheight and add to it
        </Button>
    </Wrapper>
  );
};

【讨论】:

  • 它帮助了我一点,我做了:input.current!.style.height = "32px"; in button onclick 现在它可以工作了
【解决方案2】:

根据文档

Element.scrollHeight 只读属性是元素内容高度的度量,包括由于溢出而在屏幕上不可见的内容。 https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight

根据您想要实现的目标,您可能想要使用 window.pageYOffset || document.documentElement.scrollTop 测量元素到顶部的距离, 或操作 getBoundingClientRect() 属性之一。

或者,如果您只是想减小元素尺寸,您可能需要设置固定高度并将溢出设置为滚动。

【讨论】:

    猜你喜欢
    • 2019-05-23
    • 2018-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-20
    • 1970-01-01
    • 1970-01-01
    • 2021-03-11
    相关资源
    最近更新 更多