【问题标题】:Implementation of react-intersection-observer module not working on multiple componentsreact-intersection-observer 模块的实现不适用于多个组件
【发布时间】:2022-12-22 06:34:44
【问题描述】:

我正在为“react-intersection-observer”的实施而苦苦挣扎,我终其一生都找不到解决方案。

细节:

我有一个简单的演示网站,我想用 React 来做,这样我也可以学习。现在该网站只有主页,主页目前有以下部分:标题、关于、投资组合和联系表。

我想做的是在每个部分(关于、投资组合和联系表)进入视口后简单地添加一个类。那种用 jquery 会在 2 分钟内完成的东西。

我已经安装了“react-intersection-observer”,到目前为止我的 homepage.component.jsx 中的代码如下所示:

import React from 'react';
import Header from "../../components/header/header.component";
import About from "../../components/about/about.component";
import PortfolioList from "../../components/portfolio-list/portfolio-list.component";
import ContactForm from "../../components/contact-form/contact-form.component";
import { useInView } from 'react-intersection-observer';

const HomePage = () => {
    const { ref, inView, entry } = useInView({
        /* Optional options */
        triggerOnce: true,
        threshold: 1,
        onChange: (inView, entry) => {
            console.log("salam");
            console.log(inView);
            console.log(entry);
            if (inView) {
                entry.target.classList.add("in-view");
            }
        }
    });

    return (
        <div>
            <Header/>
            <main className="main">
                <About />
                <PortfolioList />
                <ContactForm />
            </main>
        </div>
    );
};


export default HomePage;

当我像这样在每个组件上添加 ref={ref} 时:

<About ref={ref} />
<PortfolioList ref={ref} />
<ContactForm ref={ref} />

我收到一个错误:警告:函数组件不能被赋予 refs。尝试访问此 ref 将失败。你是想使用 React.forwardRef() 吗?

问题是我不想在 3 个 jsx 组件中的每一个中添加 useInView 模块,因为重复代码似乎是不好的做法。

【问题讨论】:

  • 如果您找到解决方案,请发帖

标签: reactjs react-intersection-observer


【解决方案1】:

ref 作为 props 传递是不好的做法.

使用 React.forwardRef 代替:

https://beta.reactjs.org/apis/react/forwardRef

检查这个例子:

https://beta.reactjs.org/apis/react/forwardRef#forwarding-a-ref-through-multiple-components

【讨论】:

    猜你喜欢
    • 2022-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-22
    • 2021-10-24
    • 1970-01-01
    • 1970-01-01
    • 2020-05-13
    相关资源
    最近更新 更多