我在这里面临一个非常奇怪的问题。我正在使用React-toggle依赖关系来返回某些输入的true/false值。
基本上,我正在做的是,我正在使用React-Toggle输入的回调函数来更新我的React状态值。由于某种原因,它只会更新已更改的最后一个输入,而其他输入将false。
这是我的代码外观:
RandomComponent.js
<ToggleComponent title="TestA"/>
<ToggleComponent title="TestB"/>
<ToggleComponent title="TestC"/>
<ToggleComponent title="TestD"/>
togglecomponent.js
constructor(props){
super(props);
this.state={
testA:false,
testB:false,
testC:false,
testD:false,
}
}
updateCheckValue(title){
if(title === 'TestA'){
this.setState({
testA: !this.state.testA
}, ()=>{
console.log(this.state)
})
}
if(title === 'TestB'){
this.setState({
testB: !this.state.testB
}, ()=>{
console.log(this.state)
})
}
if(title === 'TestC'){
this.setState({
testC: !this.state.testC
}, ()=>{
console.log(this.state)
})
}
if(title === 'TestD'){
this.setState({
testD: !this.state.testD
}, ()=>{
console.log(this.state)
})
}
}
render(){
return(
<Row className={styles.container}>
<Col sm={1} md={1} lg={1}></Col>
<Col sm={2} md={2} lg={2}>
<Toggle
onChange={this.updateCheckValue.bind(this, this.props.title)}
icons={false} />
</Col>
<Col sm={8} md={8} lg={8}>
<h4>{this.props.title}</h4>
</Col>
<Col sm={1} md={1} lg={1}></Col>
</Row>
)
}
您应该在此处更改该方法,状态应由 RandomComponent.js , togglecomponent.js 呼叫呼叫每次被称为。结果应该是这样的: RandomComponent.js
constructor(props){
super(props);
this.state={
testA:false,
testB:false,
testC:false,
testD:false,
}
}
updateCheckValue(att){
this.setState({
[att]: !this.state[att]
}, ()=>{
console.log(this.state)
})
}
}
render(){
<ToggleComponent title="TestA" onToggle={() => this.updateCheckValue("testA")}/>
<ToggleComponent title="TestB" onToggle={() => this.updateCheckValue("testB")/>
<ToggleComponent title="TestC" onToggle={() => this.updateCheckValue("testC")/>
<ToggleComponent title="TestD" onToggle={() => this.updateCheckValue("testD")/>
}
togglecomponent.js
<Row className={styles.container}>
<Col sm={1} md={1} lg={1}></Col>
<Col sm={2} md={2} lg={2}>
<Toggle
onChange={this.props.onToggle}
icons={false} />
</Col>
<Col sm={8} md={8} lg={8}>
<h4>{this.props.title}</h4>
</Col>
<Col sm={1} md={1} lg={1}></Col>
</Row>