react study notes for beginners
Preface
I can’t believe I’ve never learned about react before, but I’m still taking the weekend to learn about this popular framework. Although fb may not be available to us again anytime? == But it’s good to learn the idea of this framework. React was presented at f8 2014 and can be used to solve the problem of data changes in a large application. It is not a full MVC, MVVM framework and is only responsible for the view layer. It implements the principle of virtual DOM mechanism with unidirectional data binding, which enables it to respond quickly to complex data changes and interactions. It promotes componentized development , which also meets the high performance requirements of complex scenarios .
Virtual DOM with JSX
Here’s an example from the official website
1
2
3
4
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('root')
)
The ReactDOM.render is used to convert the template to HTML language and insert it into the specified DOM node. The <h1> above is essentially not really an HTML tag, but a virtual DOM. the code above is inserting the rendered result <h1> tag into the node with id root. The syntax of this HTML-JavaScript mashup is called JSX, which is essentially a syntactic sugar where every XML tag is converted into pure JavaScript code by a JSX conversion tool. The above code without JSX can be written like this:
1
2
3
4
5
// 不使用JSX
ReactDOM.render(
React.createElement('h1', null, 'Hello, world!'),
document.getElementById('root')
)
We can see that with JSX, the structure of components and the relationships between components look much clearer. Its basic syntax rule is that when you encounter an HTML tag (starting with <), you parse it with HTML rules; when you encounter a code block (starting with {), you parse it with JavaScript rules.
Components
Next we’ll try to encapsulate the component
1
2
3
4
5
class App extends Component {
render() {
return <h1 className="title">Hello {this.props.name}</h1>
}
}
1
2
3
4
ReactDOM.render(
<App name="semine" />,
document.getElementById('root')
)
1
2
3
4
.title {
color: #ff0000;
font-size: 44px;
}
The React.createClass method is used to generate a component class. The ES6 class keyword is used here for more clarity. An App is a component class and an instance of App is automatically generated when the template inserts <App />. All component classes must have their own render method for outputting components. Styles can also be written with inline styles.
1
2
3
4
5
6
7
8
9
class App extends Component {
render() {
const styleObj = {
color: '#ff0000',
fontSize: '44px'
}
return <h1 style={styleObj}>Hello {this.props.name}</h1>
}
}
Component life cycle
- Mounted A process in which a rendered component is parsed to generate a corresponding DOM node that is inserted into the browser’s DOM structure.
- Update The process by which a mounted component is re-rendered when its state changes.
- Unmounted The process of removing the DOM node corresponding to a mounted component from the DOM structure.
For each state React encapsulates a corresponding hook function
- mounting: getInitialState(ES6 does not support this method, declare it in the constructor instead)->componentWillMount->render->componentDidMount
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class App extends Component {
constructor(props) {
alert('init')
super(props)
this.state = {
color: 'blue'
}
}
componentWillMount() {
alert('will')
}
render() {
return (
<div className="App">
<div style={this.state}>state</div>
</div>
);
}
componentDidMount() {
alert('did')
window.setTimeout(() => {
this.setState({
color: 'red'
})
}, 1000)
}
}
The state here can be understood in this way: it is to think of the component as a state machine, which starts with an initial state, and then user interactions that cause the state to change, which triggers a re-rendering of the UI
- Updating: componentWillReceiveProps(when need to accept new props)->shouldComponentUpdate(compare old and new props and state, judge whether need to update)->componentWillUpdate-> render->componentDidUpdate
- Unmounting: componentWillUnmount
Listening to events
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
class TestButton extends Component {
constructor(){
super()
this.clickHandler = this.clickHandler.bind(this)
}
// 监听点击事件
clickHandler(e) {
e.stopPropagation()
e.preventDefault()
const tip = this.refs.tip
if (tip.style.display === 'none') {
tip.style.display = 'inline'
} else {
tip.style.display = 'none'
}
}
render() {
return (
<div>
<button onClick={this.clickHandler}>显示|隐藏</button><span ref="tip">点击按钮</span>
</div>
)
}
}
class Input extends Component {
constructor(props) {
super(props)
this.changeHandler = this.changeHandler.bind(this)
this.state = {
inputContent: ''
}
}
// 监听改变事件
changeHandler(e) {
e.stopPropagation()
e.preventDefault()
this.setState({
inputContent: e.target.value
})
}
render() {
return (
<div>
<input type="text" onChange={this.changeHandler}/><span>{this.state.inputContent}</span>
</div>
)
}
}
class App extends Component {
render() {
return (
<div className="App">
<Input />
<TestButton />
</div>
);
}
}
export default App
To get the real DOM node from the component, we use the ref property. In addition, the events in React.createClass are bound to the current class by default, but with es6 syntax, this points to the div’s backing instance, so we need to bind this manually to point to the current class.
Postscript
React doesn’t feel as syntactically restrictive when you write it, and there are some similarities to vue, like ref. But I prefer that it communicates the idea of a virtual DOM more clearly. Get back to the feeling of trying to learn teenage girls! Looking forward to the next update > <