Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/422.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在类组件中使用布尔状态重用函数_Javascript_Reactjs_Function_State - Fatal编程技术网

Javascript 如何在类组件中使用布尔状态重用函数

Javascript 如何在类组件中使用布尔状态重用函数,javascript,reactjs,function,state,Javascript,Reactjs,Function,State,我有5个状态和5个函数。。 状态值为 伊姆格罗:错, 错误2:错误, 错误3:错误, 错误4:错误, 错误5:错误 功能是 const erroImg = () => { this.setState({ imgError: true, }) } const erroImg2 = () => { this.setState({ imgError2: true, }) } const erroImg3 = () => { this.setSta

我有5个状态和5个函数。。 状态值为

伊姆格罗:错, 错误2:错误, 错误3:错误, 错误4:错误, 错误5:错误

功能是

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')
}

问题是,我如何使用一个函数来更改五个状态???

使用一个数组来替代处于状态的
imgError
s,并生成一个函数来返回一个更改相应索引的函数:

this.state = {
  imgErrors: new Array(5).fill(false)
};
然后,比如说,

onerror={erroImg3}
你可以

onerror={errorImg(2)}

(请记住零索引数组)

您可以通过以下操作一次更改多个状态:

const changeAllStates = () => {
    this.setState({ state1: true, state2: true, state3: false });
}
erroImg=(imgError)=>{
这是我的国家({
是的,
},()=>{
console.log(this.state.imgError1);
console.log(this.state.imgError2);
console.log(this.state.imgError3);
})
}
render(){
返回
{this.erroImg(“imgError1”)}>单击此处
{this.erroImg(“imgError2”)}>单击此处
{this.erroImg(“imgError3”)}>单击此处
;
}

谢谢你,兄弟,这对我来说太好了!!
const changeAllStates = () => {
    this.setState({ state1: true, state2: true, state3: false });
}
erroImg = (imgError) => {
    this.setState({
      [imgError]: true,
    },()=>{
        console.log(this.state.imgError1);
        console.log(this.state.imgError2);
        console.log(this.state.imgError3);
    })
  }

 render() {
  return <React.Fragment>
      <Button onClick={() => {this.erroImg("imgError1")}}>click here</Button>
      <Button onClick={() => {this.erroImg("imgError2")}}>click here</Button>
      <Button onClick={() => {this.erroImg("imgError3")}}>click here</Button>
  </React.Fragment>;
 }