change scrollTop in reactjs

前端 未结 4 1385
隐瞒了意图╮
隐瞒了意图╮ 2021-01-04 03:36

I just learn react, and want to achieve a function : both A,B are components, if A scroll, then B scroll

The following is my code

<

4条回答
  •  伪装坚强ぢ
    2021-01-04 04:12

    Here's an updated version of Season's answer, including a runnable snippet. It uses the recommended method for creating refs.

    class Editor extends React.Component {
        constructor(props) {
            super(props);
            this.content = React.createRef();
            this.handleScroll = this.handleScroll.bind(this);
        }
    
        componentDidUpdate() {
            this.content.current.scrollTop = this.props.scrollTop;
        }
        
        handleScroll() {
            this.props.onScroll( this.content.current.scrollTop );
        }
    
        render() {
            let text = 'a\n\nb\n\nc\n\nd\n\ne\n\nf\n\ng';
            return