2016-07-22 1 views
0

나는 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, 
    });  
    } 
} 

답변

1

그 동물 확인란이 선택되어, 고양이, 개, 물고기 확인란 그것의 상태와 동기화되어있을 것입니다.

또한 그것이 checkAnimal 방법으로 액세스 this.state.animal과 호환되는 jsx에서 대문자로 Athis.state.Animal 참조있다.

{this.state.Animal ? 조심해.

그런 오류를 잡기 위해 eslint와 같은 JavaScript 코드를 사용해보십시오.

+0

리팩터링 조언 주셔서 감사합니다. – lost9123193

+0

문제를 해결하는 데 도움이 되었다면 문제를 해결할 수있는 대답을 내 대답으로 표시하십시오. –