나는 Animal이라는 체크 박스가 있습니다. 체크 박스를 선택하면 this.state.Animal이 true로 설정되고 animal-filter div가 표시됩니다.체크 박스를 사용하여 상태를 동적으로 업데이트
<input type="checkbox" checked={this.state.Animal} onChange={this.checkAnimal} /> Animals
{this.state.Animal ?
<div className="animal-filter">
<div className="checkbox">
<p><input type="checkbox" checked={this.state.dog} onChange={this.checkdog} /> AA </p>
</div>
<div className="checkbox">
<p><input type="checkbox" checked={this.state.cat} onChange={this.checkcat} /> A</p>
</div>
<div className="checkbox">
<p><input type="checkbox" checked={this.state.fish} onChange={this.checkfish} /> B</p>
</div>
</div> : null}
내 문제는 내가 고양이, 개, 물고기의이 체크 박스는 동물의 상태가 true로 설정되어 즉시되면 true로 설정해야 할 것입니다. 나는 반응 setState가 상태를 자동으로 업데이트하지 않는다는 것을 안다. 어떻게하면 동물 체크 박스가 "체크 된"때 다른 체크 박스가 참으로 설정 될까?
업데이트 상태에 대한 나의 코드 : checkAnimal
방법은 크게 보장합니다
checkAnimal() {
this.setState({
animal: !this.state.animal,
cat: !this.state.animal,
dog: !this.state.animal,
fish: !this.state.animal,
});
}
이 단순화 될 수있다
checkAnimal(){
this.setState({animal: !this.state.animal});
if (this.state.animal !=true){
this.setState({
cat:false,
dog:false,
fish:false,
});
}else{
this.setState({
cat:true,
dog:true,
fish:true,
});
}
}
리팩터링 조언 주셔서 감사합니다. – lost9123193
문제를 해결하는 데 도움이 되었다면 문제를 해결할 수있는 대답을 내 대답으로 표시하십시오. –