javascript - 如何在类组件中重用具有布尔状态的函数
问题描述
我也有 5 个状态和 5 个功能.. 状态值是
imgError:假,imgError2:假,imgError3:假,imgError4:假,imgError5:假,
函数是
const erroImg = () => {
this.setState({
imgError: true,
})
}
const erroImg2 = () => {
this.setState({
imgError2: true,
})
}
const erroImg3 = () => {
this.setState({
imgError3: true,
})
}
const erroImg4 = () => {
this.setState({
imgError4: true,
})
}
const erroImg5 = () => {
this.setState({
imgError5: true,
})
console.log('tes')
}
问题是,我怎样才能使用一个功能来改变五种状态?
解决方案
对状态中的 s 使用一个数组imgError
,并创建一个函数,该函数返回一个更改相应索引的函数:
this.state = {
imgErrors: new Array(5).fill(false)
};
const errorImg = (i) => () => {
this.setState({
imgErrors: this.state.imgErrors.map(
(val, j) => j === i ? true : val
)
});
};
然后,例如,而不是
onerror={erroImg3}
你可以做
onerror={errorImg(2)}
(记住零索引数组)
推荐阅读
- terraform - 如何使用terraform中的动态键从Set中提取数据作为列表
- azure - 传入网络挂钩不支持资源过滤器
- regex - 如何编写正则表达式来匹配以特殊字符开头并以一组单词结尾的单词
- google-maps - 为什么调用 getDetails 关于 Google 地图地方库中某个地方的方法不断返回 QUERY_OVER_LIMIT 错误?
- python - 如何以可变的 dict 长度同时迭代 dict 项?
- python - 使用 OneToOneField 自动链接表单和用户
- assembly - 将 lisp 代码转换为汇编语言的工具
- file - Ant任务查找包含某个文件的所有子目录
- javascript - 如何使用我的 JavaScript 代码在 Repl.it 上使用 Telegraf 的密码?
- reactjs - 如何在 React 中观察 node.current.clientHeight 的变化?