[英]Changing class component to functional component : use method
我正在嘗試將 class 組件轉換為功能組件,但在調用子組件“Dog.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
},[])
...
}
function Dog(color, speed, total) {
Dog.resize = (stageWidth, stageHeight) => {
const gap = Math.ceil(stageWidth / (this.total - 2));
...
};
}
export default Dog;
請讓我知道如何在 App.js 中使用 Dog.js 的“resize”方法,或者我需要在我的代碼結構中進行哪些更改。 (或者只保留 class 組件的結構更好?)
要從 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.