将react-scroll-parallax的<ParallaxProvider/>应用于一个div

3
我正在尝试使用这个模块https://www.npmjs.com/package/react-scroll-parallax使react-scroll-parallax在一个div上起作用。
我试图设置视差提供程序,不仅指向body而且还指向特定的div。 我试图引用该元素(即scrollContainer)。
挑战是我在页脚和页眉之间使用了“滚动div”,所以在其上执行视差效果是行不通的。
我尝试创建一个引用,并将其引用到div上,但没有成功。
文档说要通过选项ref一个元素作为ScrollContainer: scrollContainer Element: 可选地设置具有溢出并包含视差元素的容器。 默认为HTML body
 constructor(props) {
    super(props);
    this.myScrollDiv = React.createRef();
  }

/////////////////



<ParallaxProvider scrollContainer={this.myScrollDiv.current}>
     <div className="page-scroller site-wrapper pb-5" ref={this.myScrollDiv}>
               ///Content
     </div>
</ParallaxProvider>

I would love for the .page-scroller div to handle parallax.
1个回答

0

免责声明:我从未使用过react-scroll-parallax库。答案基于源代码。

欢迎来到Stack Overflow,@stephanesng

当我查看源代码时,我发现了一个Storybook 代码片段

看起来你需要传递ref变量本身,而不是ref.current

export default class ScrollContainer extends React.Component {
    static defaultProps = {
        scrollAxis: 'vertical',
    };

    constructor() {
        super();
        this.state = {
            scrollContainer: null,
        };
        this.scrollContainer = React.createRef();
    }

    componentDidMount() {
        this.setState({ scrollContainer: this.scrollContainer.current });
    }

    render() {
        return (
            // ............ You pass the `ref` not `ref.current`                        
            <div className="scroll-container" ref={this.scrollContainer}>
                <ParallaxProvider
                    scrollContainer={this.state.scrollContainer}
                    scrollAxis={this.props.scrollAxis}
                >
                    {this.props.children}
                </ParallaxProvider>
            </div>
        );
    }
}

这意味着,您需要传递this.myScrollDiv而不是this.myScrollDiv.currentscrollContainer属性。

此外,您的ref需要放在ParallaxProvider之外。

<div className="page-scroller site-wrapper pb-5" ref={this.myScrollDiv}>
    <ParallaxProvider scrollContainer={this.myScrollDiv}>
               ///Content
    </ParallaxProvider>
</div>

如果我错了,我会删除这个答案。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接