簡體   English   中英

使用React,如何重用setState函數而不是復制和粘貼?

[英]With React, how can I reuse the setState function instead of copying and pasting?

我有一個正在制作的應用程序。 想法是您根據單擊的內容將狀態設置為不同的事物。 在這種情況下,狀態是圖像src變量。 我目前有這個...

   merryWeather = () => {
      this.setState({
         imgPath: merrys
      })
   }

   maxJPegasus = () => {
      this.setState({
         imgPath: pega
      })
   }

   betterCallLamar = () => {
      this.setState({
         imgPath: lamars
      })
   }

   betterCallLester = () => {
      this.setState({
         imgPath: lesters
      })
   }

以及其他一些狀態設置功能。 如何將它們作為一個函數編寫,並一遍又一遍地調用同一函數?

創建一個函數並傳遞要設置為imgPath的參數。

setImgPath = (imgPath) => {
  this.setState({imgPath});
}

您可以創建一個接受namevalueupdateState函數,或者為您更新imgPath的函數。

updateState = (name, value) => {
    this.setState({
        [name]: value
    });
}
merryWeahter = () => {
    this.updateState('imgPath', merrys);
}
maxJPegasus = () => {
    this.updateState('imgPath', pega);
}

要么

updateImgPath = value => {
    this.setState({
        imgPath: value
    });
}
merryWeahter = () => {
    this.updateImgPath(merrys);
}
maxJPegasus = () => {
    this.updateImgPath(pega);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM