简体   繁体   中英

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

I have an app I'm making. The idea is that you set the state to different things based off what you click. In this case, the state is the image src variable. I currently have this...

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

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

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

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

And some other state setting functions. How can I write these as one function, and call that same function over and over?

Create a single function and pass the parameter to be set as imgPath .

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

You can create an updateState function that accepts a name and value or a function that updates imgPath for you.

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

OR

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

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