[英]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.
在这种情况下,状态是图像src变量。 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
. 创建一个函数并传递要设置为
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. 您可以创建一个接受
name
和value
的updateState
函数,或者为您更新imgPath
的函数。
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.