[英]How can I reuse a function with this.setState and other component function in react native?
[英]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});
}
您可以創建一個接受name
和value
的updateState
函數,或者為您更新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.