簡體   English   中英

在 React 中將功能組件轉換為類組件

[英]Convert functional component to class component in React

我有一個應用程序正在使用類組件進行反應,我找到了一個我想添加到我的代碼中的功能代碼,但它是使用功能組件制作的。 代碼在這里https://codesandbox.io/s/framer-motion-animate-in-view-gqcc8但相關部分是這個。

import { useInView } from "react-intersection-observer";
import { motion, useAnimation } from "framer-motion";
import "./styles.css";

function Box() {
  const controls = useAnimation();
  const [ref, inView] = useInView();

  useEffect(() => {
    if (inView) {
      controls.start("visible");
    }
  }, [controls, inView]);

我不知道如何在我的類組件中添加該控件變量

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      curtains: null,
      loading: true,
      renderNav: false
    };
  }

我應該將它添加到我的狀態嗎? 我不明白如何讓它在類組件中工作

您不能在類組件內使用鈎子。 您可以做的是編寫一個小包裝器,在渲染道具中公開refcontrols

const Controls = ({children}) => {
    const controls = useAnimation();
    const [ref, inView] = useInView();

    useEffect(() => {
        if (inView) {
            controls.start("visible");
        }
    }, [controls, inView]);

    return children(ref, controls);
};

然后你可以像這樣使用它:

class App extends Component {
    // ...

    render() {
        return (
            <Controls>
                {(ref, controls) => (
                    <motion.div ref={ref} animate={controls}>
                        {/* content */}
                    </motion.div>
                )}
            </Controls>
        );
    }
}

讓我們說你有

const functionalComponent=()=>{
  return <h1>Functional componenet</h1>
}

並且您想將其更改為類組件

在頂部使用此導入:

import React,{Component} from "react";

並將您的代碼更改為如下所示:

    Class functionalComponent extends Component{
       state={}
       render(){
           return <h1>functional component</h1>;
         }
    }

您的功能組件現在更改為類組件。

並且要在現有的類組件中使用它,除非需要本地狀態,否則不需要將功能組件更改為類組件。

隨着 React 鈎子的引入,這也發生了變化,即,如果您打算使用鈎子,則不必將功能組件更改為類組件。

在您的代碼中: useEffect 是一個鈎子,您不能在類組件中使用它。

我建議在你的類組件中簡單地導入功能組件,如果你必須傳遞一些 value ,你可以將它作為一個 prop 傳遞。

就導入功能組件而言:

import React,{Component} from "react";
import Box from "./Box.js";

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      curtains: null,
      loading: true,
      renderNav: false
    };
  render(){
  return(<Box/>);
  }
  }

您還可以像類組件一樣在任何地方使用功能組件。 Btw 也在使用,因此無需擔心您無法在其中使用 state 的事情。

用:

<Box props={props}/>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM