2017-02-24 3 views
0

이 색상 선택기는 한 걸음 더 나아가지만 작동합니다. 나는 React 15.4.2를 사용 해왔다. 이후 버전에서 수정해야 할 문제입니까? 내 잘못이라면 "보류 상태 조건"을 마스터하는 방법을 알려주세요. 펜 http://codepen.io/462960/pen/qrBLje 코드 :반응 상태 업데이트 단계가 뒤로

let Input = React.createClass({ 
    getInitialState(){ 
     return { 
     today_color: "#E5D380" 
    }; 
    }, 
    colorChange(e){ 
     this.setState({ 
      today_color: e.target.value 
     }) 
     document.querySelector('html').style.setProperty('--base', this.state.today_color); 
    }, 
    render(){ 
    return (<div> 
      <input className="today_color" onChange={this.colorChange} type="color" defaultValue={this.state.today_color}/> 
      </div>) 
    } 
}) 

답변

2

당신이 겪고있는 문제는 setState를 구성 요소 rerenders를 호출하고이 코드를 다시 호출되지되면이다 : 처음

document.querySelector('html').style.setProperty('--base', this.state.today_color); 

그리고 그것은이라고합니다 this.state.today_color은 여전히 ​​이전 값입니다.

은 당신이해야 할 것은 다음

this.setState({ 
    today_color: e.target.value 
},() => document.querySelector('html').style.setProperty('--base', this.state.today_color)); 

이 setState를 완료 한 후 setProperty는이 호출되는 확인합니다 당신이 당신의 상태에서 올바른 값을 후.

편집 : 여기에있는 작업은 example입니다.

+0

답변이 수락되었고 문제가 해결되었습니다. @paqash. –

+0

실제로 받아 들여 지려면 체크 표시를 눌러야합니다. – paqash

+0

그래서 나는, @paqash를 했으므로 귀하의 요청에 조금 놀랐습니다. 규칙을 고려하여 그런 식으로 감사를 표했습니다. 그 두 개의 화살 중 하나가 나에게서 나온다. –