Add lesson 11, 12 & 13

This commit is contained in:
Kay Plößer
2016-04-28 22:19:26 +02:00
parent af7fd0de91
commit a7cd8b8dae
3 changed files with 361 additions and 0 deletions

119
11-lifecylce-methods.html Normal file
View File

@@ -0,0 +1,119 @@
<!doctype html>
<title>11 Lifecycle Methods - React From Zero</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.1/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.1/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script>
<div id='app'></div>
<script type="text/babel">
// If we use component classes, our components inherit
// a bunch of methods, which get called by React at specific
// times to allow us to get more control over our components
// a few of them we already met in lesson 9
// Here are a few new. Not all of them, but the most important ones
var TRANSLATION_FROM_SOMEWHERE = 'Text from a synchronous source.'
var MyComponent = React.createClass({
// This method is for default prop values
// it gets called before the props are given to our component
// the "real" props override them if there are any
getDefaultProps: function() {
return {
iGetOverriden: 'default',
iStayAsIAm: 'default',
}
},
// This method is called before a component got mounted to the DOM
// it returns values that are used for this.state
getInitialState: function() {
return {
serverData: null,
}
},
// This method gets called right before the component is mounted
// can be used to initialize some synchronous configuration, that should
// be available before the component renders
componentWillMount: function() {
this.TEXT = TRANSLATION_FROM_SOMEWHERE
},
// This method will be called right after the component got mounted
// it's a good place to start some asynchronous tasks.
// For example on the first mount it shows a loading message
// then componentDidMount is called and gets some server data.
componentDidMount: function() {
var component = this
// We clean up the data and get new from somewhere
function loadData() {
component.setState({serverData: null})
getServerData(function(data) {
component.setState({serverData: data})
})
}
// Initial data load
loadData()
// We simulate a server request every 4 seconds
this.updateInterval = setInterval(loadData, 4000)
},
// This method will be called before the component gets removed from the DOM
// a bit like a destructor. Here we can do some cleanup.
componentWillUnmount: function() {
clearInterval(this.updateInterval)
},
// This method is called before a render when new props or state is available
// it won't be called on the first render or if this.forceUpdate() is used
// it can be used if some state or prop changes don't require a rerender
shouldComponentUpdate: function(nextProps, nextState) {
// we want to render on every change, this is the default behaviour
return true
},
render: function() {
return <h2 style={{width: 400, margin: 'auto'}}>
Overriden Prop: {this.props.iGetOverriden}<br/><br/>
Default Prop: {this.props.iStayAsIAm}<br/><br/>
{this.TEXT}<br/><br/>
{this.state.serverData
? this.state.serverData
: 'Loading...'
}
</h2>
},
})
function getServerData(fn) {
setTimeout(function() { fn('Data Loaded!') }, 700)
}
ReactDOM.render(<MyComponent iGetOverriden={'override'}/>, document.getElementById('app'))
</script>

138
12-component-refactor.html Normal file
View File

@@ -0,0 +1,138 @@
<!doctype html>
<title>12 Component Refactor - React From Zero</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.1/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.1/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script>
<div id='app'></div>
<script type="text/babel">
// Refactoring is another thing that is nice with React
// First we'll talk about refactoring one component into another
// if you're lucky, you can just change the implementation of a component
// and don't need to change anything at the call-site
// We start with a component that renders records somehow
function ViewBefore(props) {
return <table>
<thead>
<tr>
<th>Room</th>
<th>People</th>
</tr>
</thead>
<tbody>
{props.rooms.map(function(room, k) {
return <tr key={k}>
<td>{room.name}</td>
<td>{room.people}</td>
</tr>
})}
</tbody>
</table>
}
// The component has a simple props-interface
ViewBefore.propTypes = {
rooms: React.PropTypes.array.isRequired,
}
// Now we switch out the implementation with something more complicated
function ViewAfter(props) {
return <div>
{props.rooms.map(function(room, k) {
var barStyle = {
display: 'inline-block',
background: 'lightgrey',
width: room.people * 25,
}
return <div key={k}>
{room.people > 0
? <span style={barStyle}>{room.people} People</span>
: <span>0 People</span>
}
<span> in {room.name}</span>
</div>
})}
</div>
}
// We keep the props-interface the same
ViewAfter.propTypes = {
rooms: React.PropTypes.array.isRequired,
}
// We could also switch it with something more dynamic
var ViewDynamic = React.createClass({
// We still keep the props-interface the same
propTypes: {
rooms: React.PropTypes.array.isRequired,
},
getInitialState: function() {
return {currentRoom: 0}
},
componentDidMount() {
var component = this
var props = this.props
var state = this.state
this.interval = setInterval(function() {
var currentRoom = state.currentRoom < props.rooms.length
? state.currentRoom + 1
: 0
component.setState({currentRoom: currentRoom})
}, 1000)
},
componentWillUnmount() {
clearInterval(this.interval)
},
render: function() {
var room = this.props.rooms[this.state.currentRoom]
return <span style={{color: this.state.color}}>
Room <b>{room.name}</b> has <b>{room.people}</b> People.
</span>
},
})
// Some data
var rooms = [
{name:'Office', people: 10},
{name:'Kitchen', people: 15},
{name:'Floor', people: 3},
{name:'Bathroom', people: 0},
]
// As we can see the components can be used exactly the same
// If we copy the implementation of ViewAfter into ViewBefore,
// everything keeps working
var reactElement = <div style={{margin: 'auto', width: 500}}>
<h3>Before the refactor</h3>
<ViewBefore rooms={rooms}/>
<h3>After the refactor</h3>
<ViewAfter rooms={rooms}/>
<h3>Dynamic refactor</h3>
<ViewDynamic rooms={rooms}/>
</div>
ReactDOM.render(reactElement, document.getElementById('app'))
</script>

104
13-element-refactor.html Normal file
View File

@@ -0,0 +1,104 @@
<!doctype html>
<title>12 Component Refactor - React From Zero</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.1/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.1/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script>
<div id='app'></div>
<script type="text/babel">
// Refactoring an element is a bit more tricky
// First, React decides if a tag is an element by checking its case
// lower case means element
// upper case means component
var element = <div/>
// becomes
element = React.createElement("div", null)
try {
var component = <Div/>
// becomes
component = React.createElement(Div, null)
} catch(e) {}
// Second, React converts all events, these elements trigger, to
// synthetic events. This is often not a problem, they are simply events.
// But you can't trigger your own.
// So even if your <Input> component accepts a onClick callback as property
// You can't call it with the same event as an <input> element would
// One approach could be this.
// We simply implement our own onChange caller
// Here we create a number input that only calls onChange on number inputs
// (non-numbers trigger an empty change)
var NumberInput = React.createClass({
getInitialState: function() {
return {value: ''}
},
handleInput: function(e) {
// we could try to modify the event to get or data in
// but this could mess things up
// instead we prevent this event from further actions
e.preventDefault()
var newNumber = e.target.value
// filter empty-changes
if (newNumber.length < 1 || newNumber === this.state.value) return
this.setState({value: newNumber})
//then we extract our data and give it to onChange
this.props.onChange(newNumber)
},
render: function () {
return <input type='number' value={this.state.value} onChange={this.handleInput}/>
},
})
function logChange(v){
console.log(v)
}
// Here we see, that the new NumberInput has a different interface
// it's onChange property implies that events will be received, but this isn't
// the case. Also, even if we would want to call it like the original input,
// we would need to use upper case, and wouldn't win anything
var reactElement = <div style={{width: 300, margin: 'auto'}}>
<h2>Logging number inputs</h2>
<h2>Before Refactor</h2>
<input type='number' onChange={function(e) { logChange(e.target.value) }}/>
<h2>After Refactor</h2>
<NumberInput onChange={logChange}/>
</div>
ReactDOM.render(reactElement, document.getElementById('app'))
// Other approaches include not using "default" prop names in the first place
// onUpdate instead of onChange
// It could also that a component uses onMouseDown to do something internall
// and triggers a onChange, which could cause confusion
// Often components deliver richer interactions than elements in the first place
// so their prop methods can reflect that with the name
</script>