react에서 props와 state를 마구 썼더니. 조금씩 보인다. 


비슷하긴 한데. 중요한 차이가 있다. 



전역 상수(immutable)와 같은 개념은 props를


일반 변수(mutable)과 같은 개념은 state를 사용한다. 





실제 해보니.. 



초기값은 props로 저장하고 defaultValue에 사용하고,


변수 값 (input, datetime 등의 value)를 얻기 위해 state를 사용하니 유연하다. 





자세한 내용은 아래를 참조한다. 


https://velopert.com/921



Posted by '김용환'
,



React datetime lib(https://github.com/YouCanBookMe/react-datetime) 를 사용하고 있다. 


react datetime은 내부적으로 momentjs를 사용하고 있다. 



ISO8601 데이터를 원하는 포맷(dateFormat, timeFormat)으로 맞춘다. 

<Datetime locale="ko" dateFormat="YYYY-MM-DD" timeFormat="HH:mm" 
            defaultValue={ this.props.toTime } onChange={this.changeToTime} 
            ref={(c) => this.state.toTime = c} /></td>


onChange 이벤트일 때는 내부적으로 정의한 이벤트가 아니라 momentjs 객체가 전달되는 구조이다. 




onChangefunctionempty functionCallback trigger when the date changes. The callback receives the selected moment

 object as only parameter, if the date in the input is valid. If the date in the input is not valid, the callback receives the value of the input (a string).


따라서 setState를 호출해 e.target.value 를 사용하면 value가 없다는 에러가 발생한다.


moment 객체를 이벤트로 보내기 때문이다.  


 
changeToTime(e) {
this.setState({
toTime: moment(e).format()
});
}



moment(e)로 감싸고, format()을 호출하면 변경된 시간 문자열을 얻을 수 있다.








Posted by '김용환'
,



React 16으로 컴포넌트 개발 중, input 필드를 잘 정의하고. 


<input type="text" placeholder="검색할 개수를 입력하세요." defaultValue={ this.props.number } onChange={this.changeNumber} className="form-control" ref={(c) => this.state.number = c} name="number" /></td>


event도 잘 정의했다. 

changeNumber(e) {
console.log(e)
this.setState({
number: e.target.value
});
}



Cannot read property 'setState' of undefined 라는 에러가 발생했다!!



다음과 같이 state와 event를 바인딩을 잘 했는지 잘 살펴본다. 



constructor(props) {

    super(props);


    this.state = {

        count : 1

    };


    this.changeNumber = this.changeNumber.bind(this);

}






아. 생성자에서 event 바인딩을 놓쳤다..


아래 코드를 추가하면 된다. 

this.changeNumber = this.changeNumber.bind(this);



Posted by '김용환'
,