I rewrite all the demos with ES6, some note here, source code here
If you wanna run the app, you need npm and also webpack. Enter which one you like and
npm install && webpack
then hit the index.html
Help yourself and have fun! :)
React apps are components. Each component has state(an object with data) and each is in charge of their own rendering - the render method is called whenever the state change. Here is an example for building a simple timer.
This is called before our render function. The object that is returned is assigned to this.state, we can use it via this.state.xxx.
getInitialState () {
return {
xxx: xxx,
yyy: yyy
};
}
but if you use ES6 class, there is no getInitialState method anymore, we can add it as a property in constructor.
export defalut class Timer extends React.Component {
constructor (props) {
super(props);
this.state = {
elapsed: 0
}
}
}
every time you call your method, you should use .bind(this).
componentDidMount () {
this.timer = setInterval(this.tick.bind(this), 50);
}
tick () {
this.setState({
elapsed: new Date() - this.props.start
});
}
you can prebind methods in your constructor.
constructor (props) {
super(props);
this.tick = this.tick.bind(this);
}
also you can use the arrow function
tick = () => {
// ...
}
componentDidMount is called by react when the component has been rendered on the page.
Actuall, if you are using ES6, the code block of
componentDidMountmethod can be put inside theconstructorand you don’t needcomponentDidMountany more.
One difference between the constructor and componentDidMount is that the constructor get called during server rendering too. If the interval gets set on the server, possible many times, then the server will become very busy.
This method is called immediately before the component is removed form the page and destroyed.
Let’s see how we can handle click event in React by building a navigation menu.
<input type="text" value={this.state.value} onChange={this.handleChange.bind(this)} placeholder="Type here">
Why set value as this.state.value
constructor (props) {
super(props);
this.state = {
value: "your default value"
};
}
handleChange (e) {
this.setState({
value: e.target.value.substr(0, 140)
});
}
The real power of React comes when you combine multiple components.
How to communicate betweeen components
This example will demonstrate how you can combine react with jQuery. and how to load results via Ajax
use this this.favoriteClick.bind(this)(id) if you no autobinding your method