0
我有一個名爲Animal的複選框。當選中該複選框時,將this.state.Animal設置爲true,並顯示animal-filter div。使用複選框使用React動態更新狀態
<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不會自動更新狀態,所以我怎麼做,當動物複選框被選中時,其他複選框被設置爲true,反之亦然?
我的更新狀態代碼:
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
沒問題,請考慮標記我的答案作爲接受的答案,如果它幫助您解決問題! –