一、React新的前端思維方式
第一章:主要簡單的介紹了下通過create-react-app來創(chuàng)建自己的react組件吧; create-react-app是通過npm發(fā)布的安裝包,確認(rèn)node和npm安裝好了之后,執(zhí)行→npm install --global create-react-app 就可以了。
安裝create-react-app之后,可以通過執(zhí)行→ create-react-app 加上“文件夾名字” 就可以創(chuàng)建默認(rèn)的react組件了。
※1. import 是es6語法中的導(dǎo)入文件塊的方式。es6語法是一個(gè)大集合。大部分語法功能都被最新的瀏覽器支持。
※2.component作為組件的基類,提供了很多組件共有的功能 例如→ class ClickCounter extends Component{ } :就是創(chuàng)建一個(gè)clickcounter組件,component是clickcounter的父類。
import React, { Component } from 'react';
class ClickCounter extends Component {
constructor(props) {
super(props);
this.onClickButton = this.onClickButton.bind(this);
this.state = {
count: 0
}
}
onClickButton() {
this.setState({count: this.state.count + 1});
}
render() {
const counterStyle = {
margin: '16px'
}
return (
<div style={counterStyle}>
<button onClick={this.onClickButton}>Click Me</button>
<div>
Click Count: <span id="clickCount">{this.state.count}</span>
</div>
</div>
);
}
}
export default ClickCounter;
※3.import React ,{Component} from "react"; 需要知道的是,在有jsx的時(shí)候,必須要導(dǎo)入React。因?yàn)閖sx最終會被轉(zhuǎn)譯依賴于React的表達(dá)式。
(所謂的jsx是JavaScript的語法擴(kuò)展,讓我們在JavaScript中可以編寫像html一樣的代碼;React判斷一個(gè)元素是HTML還是jsx原則就是看第一個(gè)字母是否大寫,所以組件要注意首字母大寫。)
※4. 也就是react的奧義理念吧 歸結(jié)為一個(gè)公式(數(shù)據(jù)驅(qū)動(dòng)渲染):
UI= render(data);函數(shù)為純函數(shù),什么是純函數(shù),就是正經(jīng)函數(shù),沒其他多余副作用,輸出完全依賴于輸入的函數(shù)。
※5.Dom樹是html的抽象,而Virtual Dom就是對Dom樹的抽象。
(virtual Dom不會觸及瀏覽器的部分,只存在于JavaScript空間的樹形結(jié)構(gòu),每次自上而下的渲染React組件的時(shí)候,會對比這一次產(chǎn)生的Virtual Dom 和上一次的Virtual Dom,對比就會發(fā)現(xiàn)差別,然后修改真正的DOM樹時(shí)就只需要觸及差別中的部分就可以了)