简体   繁体   English

如何在反应中用鼠标滚轮水平滚动表格?

[英]How to horizontally scroll a table with mouse wheel in react?

I want to enable the mouse wheel to scroll the table horizontally.我想让鼠标滚轮水平滚动表格。

How can I do it?我该怎么做?

CSS CSS

table {
  border-collapse: collapse;
  border-spacing: 0;
  width: 100%;
  border: 1px solid #ddd;
}

th, td {
  text-align: left;
  padding: 8px;
}

.container {
  overflow-x: auto;
}


tr:nth-child(even){background-color: #f2f2f2}

logic code:逻辑代码:


function App() {
  const num = 50;
  let points_th = [];

  for(let i = 0; i < num; i++ ) {
    points_th.push(<th>Points</th>);
  }

  let row_1 = render_row('Jill', 'Smith', 50, num);
  let row_2 = render_row('Eva', 'Jackson', 94, num);
  let row_3 = render_row('Adam', 'Johnson', 67, num);
  return (
      <div>
        <div className='container'>
          <table>
            <tr>
              <th>First Name</th>
              <th>Last Name</th>
              {points_th}
            </tr>
              {row_1}
              {row_2}
              {row_3}
          </table>
        </div>
      </div>
  );
}

here is my demo: https://codesandbox.io/s/github/Kalipts/scroll_table这是我的演示: https://codesandbox.io/s/github/Kalipts/scroll_table

Use onWheel event使用onWheel 事件

The onwheel event occurs when the mouse wheel is rolled up or down over an element. onwheel事件在鼠标滚轮在元素上向上或向下滚动时发生。

With Element.scrollTo() , Element.scrollLeft使用Element.scrollTo()Element.scrollLeft

The scrollTo() method of the Element interface scrolls to a particular set of coordinates inside a given element. Element 接口的scrollTo()方法滚动到给定元素内的一组特定坐标。

element.scrollTo({
  top: 100,
  left: 100,
  behavior: 'smooth'
});

Code sample:代码示例:

const onWheel = e => {
  e.preventDefault();
  const container = document.getElementById("container");
  const containerScrollPosition = document.getElementById("container").scrollLeft;
  container.scrollTo({
    top: 0,
    left: containerScrollPosition + e.deltaY,
    behaviour: "smooth"
  });
};

<div className="container" id="container" onWheel={onWheel}>

在此处输入图像描述

Refer: Horizontal Scrolling on React Component Using Vertical Mouse Wheel参考: 使用垂直鼠标滚轮在 React 组件上水平滚动

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM