javascript - 如何让这个元素类在 React 中滚动时发生变化?

标签 javascript reactjs

当您在元素上方滚动 100 像素或更少时,我希望 div 元素获得“showtext”类。当您在其上方 100 像素或更多时,它具有“隐藏”类别。

我正在尝试使用 ref 来访问 div 元素,并使用名为 showText 的方法来检查并查看何时滚动到该 div 元素上方 100 像素或更少,我为此使用了scrollTop。

然后我使用 componentDidMount 添加滚动的窗口事件监听器,并调用我的 showText 方法。

我对此很陌生,所以我确信这里存在错误,并且可能是错误的代码。但如有任何帮助,我们将不胜感激!

import React, {Component} from 'react';

class SlideIn extends Component{

    state={
        showTexts: false,
    }

    showText=()=>{
        const node= this.showTextRef;
        if(node.scollTop<=100)
        this.setState({
            showTexts: true
        })
    }



    componentDidMount(){
        window.addEventListener('scroll', this.showText() )
    }



    render(){
        const intro= document.querySelector('.intro')
        return(
            <div classname={this.state.showTexts ? 'showText' : 'hidden'} ref={node =>this.showTextRef = node}>
             {window.addEventListener('scroll', this.showText)}


                <h1>You did it!</h1> 
            </div>
        )
    }
}

export default SlideIn

我尝试在窗口滚动事件中使用 this.showText ,正如您在上面看到的 this.showText() ,两者都不起作用。我尝试在 showText 方法中使用 div 引用上的 current 属性,但它抛出了一个错误,指出scrollTop 无法定义 null 属性。

我再次对此感到陌生,从未以这种方式添加窗口事件监听器,也从未使用过scrollTop。

感谢您的帮助!

最佳答案

当您附加事件监听器时,您必须传递一个函数作为参数。当您添加事件监听器时,您将直接调用该函数。

本质上,你需要改变:

componentDidMount(){
    window.addEventListener('scroll', this.showText() )
}

至:

componentDidMount(){
    window.addEventListener('scroll', this.showText)
}

在滚动监听器中,您应该检查窗口的滚动位置(这是您执行滚动的元素):

showText = () => {
    if (window.scrollY <= 100) {
        this.setState({
            showTexts: true
        });
    }    
}

此外,您还在 render 方法中附加事件监听器。 render 方法应该只包含渲染元素的逻辑。

关于javascript - 如何让这个元素类在 React 中滚动时发生变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56593357/

相关文章:

javascript - Bundle.js ReactJS 文件美化

javascript - react native : is it possible to stop PanResponder event inside onPanResponderMove?

css - 在 React 中水平对齐几个组件

html - 有一个 iframe 标签覆盖整个页面,阻止与应用程序交互

javascript - Chrome 扩展 : Interacting with iframe embedded within popup

javascript - 展平由 JavaScript 中的嵌套元素分组的数组

javascript - stdin.write 抛出错误 : write EPIPE

javascript - 在 Chrome 中以编程方式重新加载 javascript 资源

reactjs - React 使用 JSX 和 ES6 加载动态模板

javascript - 三个 J 中的交互式网格