【问题标题】:Forward Parent onWheel to Scroll Table将父级 ​​onWheel 转发到滚动表
【发布时间】:2018-05-28 18:37:03
【问题描述】:

我有一个外部父级 <div /> 容器,其中包含一个 <Table /> 元素。我希望能够滚动父 <div /> 元素的 onWheel 事件上的 <Table />,即使鼠标当前不在 <Table /> 上。

我有一个对表格元素的引用和一个监听 onWheel 事件的事件处理程序,但我无法弄清楚如何将该事件转发到表格。

【问题讨论】:

  • 你能告诉我们你到目前为止的尝试吗?
  • 可能使用 .scrollTo 函数来触发表格滚动,但您必须进行一些计算
  • @monssef 是的,这是我的想法……不过,如果可能的话,我想避免这种情况。部分是因为它看起来不必要地复杂,部分是因为我不知道计算会是什么样子。

标签: reactjs react-virtualized


【解决方案1】:

因为我猜你想滚动表格体,你可以试试这个。

class Table extends React.Component {

    constructor() {
        super();
        this.callback = this.callback.bind(this);
        this.body = null;
    }

    callback(ev) {
        
        this.body.scrollTop += ev.deltaY;
    }
    
    render() {
        return <div onWheel={this.callback}>
            <table>
                <tbody ref={c => this.body = c}>
                    {[1, 2, 3, 4, 5, 6,].map(i => <tr>
                        <td>{i}</td>
                    </tr>)}
                </tbody>
            </table>
        </div>;
    }
}

ReactDOM.render(<Table />, document.getElementById('root'));
tbody {
  display: block;
  height: 3rem;
  overflow: scroll;
}

tr:nth-child(2n+1) {
  background-color: #ddf;
}

tr:nth-child(2n) {
  background-color: #eef;
}

table {
  margin: auto;
  border-collapse: collapse;
}

td {
  width: 5rem;
  text-align: center;
  font-family: sans-serif;
  color: #00f;
}

div {
  width: 100%;
  display: block;
  text-align: center;
  background-color: #99f;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

【讨论】:

  • 这有 react-virtualized 标签,我希望答案能够利用内置 API,而不是下拉到 DOM 方法。
【解决方案2】:

我发了codePen illustrating a scroll redirection

这将在父&lt;div&gt;(带有红色背景的那个)上监听wheelEvent,禁用默认滚动行为(evt.preventDefault())然后设置另一个&lt;div&gt;scrollTop位置。

这是组件代码:

class RedirectScroll extends React.Component {
    parentOnScroll = (evt) => {
        evt.preventDefault();
        const scrollTo= (evt.deltaY) + this.box.scrollTop;
        this.box.scrollTop = scrollTo;
    }
    render() {
        return (
            <div className="parent" onWheel={this.parentOnScroll}> // Listen scrolls on this div
               <div className="scrollablebox" ref={(box) => this.box = box}>
                   // Some content
               </div>
            </div>
        );
    }
}

我希望这就是你要找的。​​p>

【讨论】:

  • 这有 react-virtualized 标签,我希望答案能够利用内置 API,而不是下拉到 DOM 方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-17
  • 1970-01-01
  • 1970-01-01
  • 2020-01-05
  • 2016-06-26
  • 1970-01-01
  • 2020-12-09
相关资源
最近更新 更多