【问题标题】:React - Changing functional component to class componentReact - 将功能组件更改为类组件
【发布时间】:2021-03-24 10:34:51
【问题描述】:

我有一段代码用到了一个函数组件,包括useEffect等,我想把这段代码转换成一个类,请帮忙

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>
  );
}

【问题讨论】:

  • 您应该尝试展示您的尝试以及您遇到的问题,以便有人可以帮助您。
  • 我已经演示了要转换为类组件的代码

标签: javascript reactjs function class components


【解决方案1】:

这是到 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>
    );
  }
}

您应该考虑到函数和类组件的工作方式并不完全相同,但是由于存在一些各自的方面(并且您应该了解它以便您自己做!)我们可以从一个函数...

就像这里的朋友说的......你应该学习,自己尝试,当你真的陷入困境时再在这里问。仔细阅读this article

【讨论】:

    猜你喜欢
    • 2022-11-30
    • 2020-06-22
    • 1970-01-01
    • 2018-06-08
    • 2021-03-02
    • 2020-12-21
    • 1970-01-01
    • 1970-01-01
    • 2021-04-06
    相关资源
    最近更新 更多