Forward parent table to scroll table

I have an external parent container <div />containing the item <Table />. I would like to scroll <Table />in the event of the onWheelparent element <div />, even if the mouse is not currently over <Table />.

I have a reference to the table element and an event handler that listens for the onWheel event, but I could not figure out how to redirect this event to the table.

+4
source share
2 answers

I made a codePen illustrating scroll redirection

wheelEvent <div> (, ), (evt.preventDefault()), scrollTop <div>.

:

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

, , .

+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>
+1

Source: https://habr.com/ru/post/1690796/


All Articles