簡體   English   中英

如何使用 React.js 的向上和向下按鈕在文本區域中逐行向上和向下滾動

[英]How to scroll up and down line by line in a textarea using up and down buttons with React.js

我有一個 textarea 和兩個按鈕(向上和向下)。

如何使用 React.js 的向上和向下按鈕在文本區域中逐行滾動。

就好像我正在寫一個筆記,然后我使用鍵盤上的向上和向下鍵在段落中上下移動文本光標。

圖片: https ://i.stack.imgur.com/9eEXU.png

簡化代碼:

    import React from "react";
    
    export default function App() {
      return (
        <div>
          <button>Up</button>
          <br />
          <textarea placeholder="YOUR NOTES" />
          <br />
          <button>Down</button>
        </div>
      );
    }

一個朋友幫我解決了。 我想我應該回到這里與將來可能需要它的其他人分享解決方案。

import React from "react";

const goUp = (id) => {
  var maxScrollTop = id.scrollHeight - id.clientHeight;
  if (id.scrollTop !== 0) {
    id.scrollTo({
      top: id.scrollTop - 10,
      left: 0,
      behavior: "smooth"
    });
  }
};
const goDown = (id) => {
  var maxScrollDown = id.scrollHeight - id.clientHeight;
  id.scrollTo({
    top: id.scrollTop + 10,
    left: 0,
    behavior: "smooth"
  });
};

export default function App() {
  const okay = document.getElementById("text");
  return (
    <div>
      <button onClick={() => goUp(okay)}>Up</button>
      <br />
      <textarea id="text" placeholder="YOUR NOTES" />
      <br />
      <button onClick={() => goDown(okay)}>Down</button>
    </div>
  );
}
I will recommend to pass function like that.

import * as React from 'react';
import './style.css';

export default function App() {
  return (
      <div>
      <button onClick={goUp}>Up</button>
      <br />
      <textarea id="notes"  placeholder="YOUR NOTES" />
      <br />
      <button onClick={goDown}>Down</button>
    </div>
  );
}

const goUp = () => {
  
  const id = document.getElementById("notes");
  var maxScrollTop = id.scrollHeight - id.clientHeight;
  if (id.scrollTop !== 0) {
    id.scrollTo({
      top: id.scrollTop - 10,
      left: 0,
      behavior: "smooth"
    });
  }
};
const goDown = () => {
  const id = document.getElementById("notes");

  var maxScrollDown = id.scrollHeight - id.clientHeight;
  id.scrollTo({
    top: id.scrollTop + 10,
    left: 0,
    behavior: "smooth"
  });
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM