change scrollTop in reactjs

前端 未结 4 1408
隐瞒了意图╮
隐瞒了意图╮ 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

    There are a number of patterns to achieve this. This sample is what I came up with to get you up and going.

    First create a component class which has an oversize element for scroll effect. When dragging the scroll bar, this component calls its handleScroll React property to notify its parent component, with the value of scrollTop.

    var Elem = React.createClass({
        render() {
            return (
                
    Hello!
    ); }, componentDidUpdate() { this.refs.elem.scrollTop = this.props.scrollTop; }, onScroll() { this.props.handleScroll( this.refs.elem.scrollTop ); } });

    The parent component, aka wrapper, keeps the scroll top value in its state. Its handleScroll is passed to the child components as callback. Any scroll on the child elements triggers the callback, sets the state, results in a redraw, and updates the child component.

    var Wrapper = React.createClass({
        getInitialState() {
            return {
                scrollTop: 0
            }
        },
        render() {
            return (
                
    ); }, handleScroll( scrollTop ) { this.setState({ scrollTop }); } });

    And render the wrapper, presuming an existing

    .

    ReactDOM.render(
        ,
        document.getElementById('container')
    );
    

提交回复
热议问题