首页 > 解决方案 > 如何在类组件中重用具有布尔状态的函数

问题描述

我也有 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')
}

问题是,我怎样才能使用一个功能来改变五种状态?

标签: javascriptreactjsfunctionstate

解决方案


对状态中的 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)}

(记住零索引数组)


推荐阅读