简体   繁体   English

将class组件改成功能组件:使用方法

[英]Changing class component to functional component : use method

I am trying to convert class component to functional component, but having a trouble calling method 'resize' of child component 'Dog.js'我正在尝试将 class 组件转换为功能组件,但在调用子组件“Dog.js”的方法“调整大小”时遇到问题

  1. App.js应用程序.js
function App(props) {
  useEffect(() => {
    const dogs = [
      new Dog("#fff", 1, 2)
    ]

    dogs[0].resize(stageWidth, stageHeight) // here is what I want to perform - now it is undefined

   },[])
 ...
 }

  1. Dog.js狗.js

function Dog(color, speed, total) {

  Dog.resize = (stageWidth, stageHeight) => {
      const gap = Math.ceil(stageWidth / (this.total - 2));
      ...
  };

}
export default Dog;

please let me know how to use the 'resize' method of Dog.js in App.js, or what i need to change in my code structure.请让我知道如何在 App.js 中使用 Dog.js 的“resize”方法,或者我需要在我的代码结构中进行哪些更改。 (or just keeping the structure of class component is better?) (或者只保留 class 组件的结构更好?)

To call resize Dog.js method from App.js you need to change Dog function like this:要从 App.js 调用 resize Dog.js 方法,您需要像这样更改 Dog function:

function Dog(color, speed, total) {

  this.resize = (stageWidth, stageHeight) => {
      const gap = Math.ceil(stageWidth / (this.total - 2));
      ...
  };

}
export default Dog;

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

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