简体   繁体   中英

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

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.

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...

Like the friends here said... You should learn, try by yourself, and when you are really stuck then ask here. Read this article carefully

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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