Tutorial
A Javascript UI Framework
HTML
Javascript
CSS
DOM
Structure
Style
interactive
effect
+
+
Traditional Web View
With MVC
Everything is Component
<html>
<head>
<title>Sample App</title>
</head>
<body>
<div id="root"><!-- CONTENT --></div>
</body>
<script src="bundle.js"></script>
</html>
HTML ENTRY
public/index.html
Render
Target
JSBundle by Webpack
var React = require('react');
var ReactDOM = require('react-dom');
var Demo = require('./demo');
function render () {
ReactDOM.render(
( <Demo /> ),
document.getElementById('root'));
}
render();
Application
src/app.jsx
VDOM -> DOM
React component (JSX)
var React = require('react');
const Demo = React.createClass({
getInitialState () {
return{
data: 'Hello world';
}
},
handleClick(e){
console.log("I've been click");
},
render(){
return(
<div onClick={this.handleClick}>
{this.state.data}
</div>
);
}
});
export default Demo;
React component
src/demo.jsx
set state
VDOM
<Input type="text" key={object.id} ref="nameInput" anyprops={this.state.data} >
10 min
Thinking : 如果是10個有些微不同的input呢?
this.setState({ state : newState })
Whenever you call, component reRender
getInitialState () {
return {
data: 'initial data'
}
},
//parent
<Test data="123"/>
//child
this.props.data => "123"
constructor(props){
super(props);
this.state = {data: props.data}
}
render(){
return(<div>{this.state.data}</div>)
}
或者
render(){
return(<div>{this.props.data}</div>)
}
TRY IT ?
constructor(props){
super(props);
this.state = {data: props.data}
}
render(){
return(<div>{this.state.data}</div>)
}
或者
render(){
return(<div>{this.props.data}</div>)
}
When parent props change, the first way nothing happened. WHY?
VERY important
Practice :
Log it whenever you use lifecycle method
//parent
callback(returnData){
this.state.data = returnData;
this.setState({ data:this.state.data});
},
render(){
return(
<Test returnValue={this.callback} />
);
}
//child
let data = '123';
this.props.returnValue(data);
When parent want child's data
10 min
Hint : component reuse