简体   繁体   中英

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'

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

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. (or just keeping the structure of class component is better?)

To call resize Dog.js method from App.js you need to change Dog function like this:

function Dog(color, speed, total) {

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

}
export default Dog;

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