javascript - Zmena scrollHeight inej komponenty


Mám komponent takto:

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

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

Potrebujem zmeniť scrollHeight vstupu po kliknutí na tlačidlo, takže som sa pokúsil použiť useRef, ale dostávam chybu: Cannot assign to 'scrollHeight' because it is a read-only property. Ako to môžem opraviť?

Odpoveď č. 1

Nemám veľa, z čoho by som vychádzal z toho, čo ste napísali, ale niečo takéto by mohlo pomôcť:

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>
  );
};

Odpoveď č. 2

Podľa dokumentov

Vlastnosť Element.scrollHeight len na čítanie je mierou výšky obsahu prvku, vrátane obsahu, ktorý nie je viditeľný na obrazovke kvôli pretečeniu. https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight

V závislosti od toho, čo chcete dosiahnuť, možno budete chcieť použiť window.pageYOffset || document.documentElement.scrollTop na zmeranie vzdialenosti prvku od vrchu, alebo manipulovať s jednou z vlastností metódy getBoundingClientRect().

Alebo možno, ak chcete len zmeniť rozmery prvku, môžete nastaviť pevnú výšku a nastaviť pretečenie na posúvanie.