開始實習後公司技術棧是偏React的,提及來也是慚愧,一個學前端的小崽崽竟然這麼久都沒有用過,這幾天開始學習了一下其實我的感受React仍是比Vue用的舒服一些(理解層面上),提及來畢竟前者的維護社區團隊但是臉書呀。好了廢話很少說了總結一下React基礎(結合官網順序,附帶上本身的一些理解作個記錄,後面也包括hook),我儘可能每個點都附上一個案例這樣能夠更好的理解。javascript
js的一種擴展語法,簡單來說有了這種拓展語法的支持咱們就能夠在js中直接書寫html代碼。咱們後面知道React就是基於.js文件不像Vue中html部分有專門的包裹,因此JSX在這之中確定是可以用到的。html
const el = <div>我是一個JSX對象</div>
複製代碼
React 怎樣將你所寫渲染到界面上?前端
咱們結合 ReactDOM.render()
方法鏈接DOM與咱們的React元素。java
// html中<div id="root"></div>
const el = <div>我是一個JSX對象</div> ReactDOM.render(el, document.getElementById('root')); 複製代碼
怎樣更新渲染?jquery
更新渲染時內部會有一個比對,得出結果後就只更新有修改的一部分,這一部份內部原理重要性可想而知,小編先放一下後續看源碼在去寫一下git
function Show(props) {
return <h1>Hello, React</h1>; } 複製代碼
class Show extends Render.Component {
render( return <h1>Hello, React</h1>; ) } 複製代碼
這裏是我以爲比較舒服的一個點,咱們經過 props
進行參數傳遞,他不止能夠拿到咱們從父組件傳遞過來的值,一樣能夠拿到 JSX
所定義屬性,props
是不可改變的。github
function Show(props) {
return <h1>Hello, {props.name}</h1>; } const el = <Show name="sichen"/> 複製代碼
私有變量要用到他的話咱們要以class聲明到內部使用,state是沒法直接更改的,咱們只能經過setState()對他進行一個更改,構造函數是惟一能夠給 this.state 賦值的地方。web
class Show extends Render.Component {
constructor(props) { super(props); this.state = { name: 'sichen' } } render( return <h1>Hello, {this.state.name}</h1>; ) } 複製代碼
同時也要注意到的一個點是,this.props 和 this.state 可能會異步更新,因此在setState()中最好不要直接去改props的值。咱們能夠經過參數傳遞實現api
this.setState((state, props) => ({
counter: state.counter + props.increment })); 複製代碼
state
向下傳遞數組
毫無疑問生命週期無疑是都是框架內最爲重要的點
React中生命週期主要是分爲三大塊,下面也放上了每一塊對應的一些方法
Mounting:插入真實 DOM
Update:從新渲染
Unmount:移出真實 DOM
<!-- fn爲綁定的事件方法 -->
<button onClick={fn}> Activate Lasers </button> 複製代碼
咱們這邊要注意一下咱們日常實際情景上在內部定義方法後都有回調將方法丟出去,this指向問題要注意一下一般咱們直接用箭頭函數就行了
<!-- fn爲綁定的事件方法 -->
<button onClick={() => this.fn}> Activate Lasers </button> 複製代碼
這邊放上一個請求數據的一個案例,有結合到生命週期那一塊就比較貼合。從數據請求到拿到數據的界面顯示。
<!-- jquery部分和React已導入的,未附上 -->
<div id="example"></div> <script type="text/babel"> class RepoList extends React.Component { constructor(props) { super(props) this.state = { loading: true, error: null, data: null }; } componentDidMount() { this.props.promise.then( value => this.setState({loading: false, data: value}), error => this.setState({loading: false, error: error})); } render() { if (this.state.loading) { return <span>Loading...</span>; } else if (this.state.error !== null) { return <span>Error: {this.state.error.message}</span>; } else { var repos = this.state.data.items; var repoList = repos.map(function(repo, index) { return ( <li key={index}><a href={repo.html_url}>{repo.name}</a> ({repo.stargazers_count} stars) <br/> {repo.description}</li> ); }); return ( <main> <h1>Most Popular JavaScript Projects in Github</h1> <ol>{repoList}</ol> </main> ); } } } ReactDOM.render( <RepoList promise={$.getJSON('https://api.github.com/search/repositories?q=javascript&sort=stars')} />, document.getElementById('example') ); 複製代碼
這個案例裏面就涵蓋了挺多的也比價符合實際案例,感受總體看下來應該會比較有收穫。這邊的話主要就是對 React
基礎部分作了一個整理,應該仍是有些遺漏的。後續會在進行整理。