JSFiddle - React, Tailwind, and code Playground
HTML
<script src="http://fb.me/react-with-addons-0.12.0.js"></script>
<div id="app"></div>
JavaScript
/* var Hello = React.createClass({
render: function() {
return React.DOM.div({}, 'Hello ' + this.props.name);
}
});
Hello = React.createFactory(Hello);
React.render(Hello({name: 'World'}), document.body); */
// 부모:<Parent /> 정의
var Parent = React.createClass({
// State(※상태는 부모가 관리) // 이 값은 브라우저를 닫거나 리로드 할 때까지 보존된다
getInitialState: function () {
return {
textVal: "",
children: []
};
},
// State(textVal)의 변환
setStateTextVal: function(textVal) {
this.setState({ textVal: textVal });
},
// State(children)을 변경
setStateChildren: function(textVal) {
var textVals = this.state.children.concat(textVal);
this.setState({ children: textVals });
},
// <Parent />의 표시
// 여기서 자식이 되는<ChildInput />과<Child />을 기술
render: function() {
return (
<div>
<p>入力してEnterキーを押す</p>
<ChildInput onChange={this.setStateTextVal} onSave={this.setStateChildren} />
<Child textVal={this.state.textVal} children={this.state.children} />
</div>
);
}
});
// 자식1:<ChildInput />의 정의(※props를 통해 부모를 참조할 수 있다)
var ChildInput = React.createClass({
_onChange: function (e) {
this.props.onChange(e.target.value);
},
_onKeyDown: function (e) {
if (e.keyCode === 13) { // Enter키
this.props.onSave(e.target.value);
e.target.value = "";
}
},
// <ChildInput />의 표시
render: function() {
return <input type="text" onChange={this._onChange} onKeyDown={this._onKeyDown} />;
}
});
// 자식2:<Child />의 정의(※props통해서 부모를 참조할 수 있다)
var Child = React.createClass({
// <Child />의 표시
render: function() {
var key = 0; var textVals = this.props.children.map(function (textVal) {
// 시간이 같다. 즉 키가 눌러질 때마다 한꺼번에 재묘사 되고 있는 점에 주목
//(서버사이드와 닮아있다고 평가되는 이유)
var date = new Date().toString();
return <li key={key++}>{key}.{textVal}({date})</li>;
});
return (
<div>
<p>{this.props.textVal}</p>
...