简体   繁体   English

React - 将功能组件更改为 class 组件

[英]React - Changing functional component to class component

I have some code where a functional component is used, including useEffect and so on, I want to convert this code to a class, please help我有一些使用功能组件的代码,包括useEffect等,我想将此代码转换为class,请帮助

import * as React from "react";

export default function App() {
  const [isGreaterThan900px, setIsGreaterThan900px] = React.useState(false);

  React.useEffect(() => {
    function handleResize() {
      if (window.innerWidth > 900) {
        setIsGreaterThan900px(true);
      } else {
        setIsGreaterThan900px(false);
      }
    }

    handleResize();

    window.addEventListener("resize", handleResize);

    return () => window.removeEventListener("resize", handleResize);
  }, []);

  return (
    <div className="App">
      <h1>is greater than 900 px: {isGreaterThan900px ? "true" : "false"}</h1>
    </div>
  );
}

This is a RAW conversion to a React Class component.这是到 React Class 组件的 RAW 转换。

import * as React from "react";
import { setState } from "react";

export default class App extends React.Component {
  constructor(props) {
    super(props);

    this.handleResize = this.handleResize.bind(this.handleResize);

    this.state = {
      isGreaterThan900px: false
    };
  }

  handleResize() {
    if (window.innerWidth > 900) {
      this.setState({ isGreaterThan900px: true });
    } else {
      this.setState({ isGreaterThan900px: false });
    }
  }

  componentDidMount() {    
    this.handleResize();
    window.addEventListener("resize", this.handleResize);
  }

  componentDidUpdate() {    
    this.handleResize();
    // window.addEventListener("resize", this.handleResize);   <---- you should not create another listener on update because there is one already running since the component did mount
  }

  componentWillUnmount() {
    window.removeEventListener("resize", this.handleResize);
  }

  render() {
    return (
      <div className="App">
        <h1>
          is greater than 900 px: {this.state.isGreaterThan900px ? "true" : "false"}
        </h1>
      </div>
    );
  }
}

You should take in count that function and class components don't work the same exactly, but since there are some respective aspects (and you should learn about it so you could do it yourself.) we can make a class out of a function... You should take in count that function and class components don't work the same exactly, but since there are some respective aspects (and you should learn about it so you could do it yourself.) we can make a class out of a function. ..

Like the friends here said... You should learn, try by yourself, and when you are really stuck then ask here.就像这里的朋友说的......你应该学习,自己尝试,当你真的卡住的时候再在这里问。 Read this article carefully仔细阅读 这篇文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM