日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問(wèn)題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
從 Vue2.0 到 React17 —— React 開(kāi)發(fā)入門

 前言

找工作時(shí)發(fā)現(xiàn)有一些公司是以React作為技術(shù)棧的,而且薪資待遇都不錯(cuò),為了增加生存的籌碼,所以還是得去學(xué)一下React,增加一項(xiàng)求生技能。因?yàn)槲矣肰ue2.0開(kāi)發(fā)項(xiàng)目已經(jīng)四年了,故用Vue2.0開(kāi)發(fā)項(xiàng)目的思路來(lái)學(xué)習(xí)React。

公司主營(yíng)業(yè)務(wù):成都網(wǎng)站制作、成都網(wǎng)站設(shè)計(jì)、移動(dòng)網(wǎng)站開(kāi)發(fā)等業(yè)務(wù)。幫助企業(yè)客戶真正實(shí)現(xiàn)互聯(lián)網(wǎng)宣傳,提高企業(yè)的競(jìng)爭(zhēng)能力。創(chuàng)新互聯(lián)建站是一支青春激揚(yáng)、勤奮敬業(yè)、活力青春激揚(yáng)、勤奮敬業(yè)、活力澎湃、和諧高效的團(tuán)隊(duì)。公司秉承以“開(kāi)放、自由、嚴(yán)謹(jǐn)、自律”為核心的企業(yè)文化,感謝他們對(duì)我們的高要求,感謝他們從不同領(lǐng)域給我們帶來(lái)的挑戰(zhàn),讓我們激情的團(tuán)隊(duì)有機(jī)會(huì)用頭腦與智慧不斷的給客戶帶來(lái)驚喜。創(chuàng)新互聯(lián)建站推出屏山免費(fèi)做網(wǎng)站回饋大家。

前端項(xiàng)目是由一個(gè)個(gè)頁(yè)面組成的,對(duì)于Vue來(lái)說(shuō),一個(gè)頁(yè)面是由多個(gè)組件構(gòu)成的,頁(yè)面本身也是一個(gè)路由組件。對(duì)于React來(lái)說(shuō)也是如此。Vue會(huì)提供一系列技術(shù)支持來(lái)完成一個(gè)組件的開(kāi)發(fā),可以從這一系列技術(shù)支持出發(fā),去React中尋找對(duì)應(yīng)的技術(shù)支持來(lái)入門React,比如React中如何開(kāi)發(fā)組件的UI,React中如何使用組件,React中如何定義組件數(shù)據(jù)等等。

本專欄將按照這個(gè)思路帶領(lǐng)你從Vue2.0入門React17。

1、腳手架

首先得選擇一個(gè)腳手架搭建一個(gè)React工程,React有很多腳手架,為什么選擇UmiJS這個(gè)腳手架,不為什么,這個(gè)腳手架和Vue Cli比較類似,至少路由配置和Vue Router很類似。

在學(xué)習(xí)前,先用UmiJS搭建一個(gè)React工程,步驟很簡(jiǎn)單:

  •  先找個(gè)地方建個(gè)空目錄,打開(kāi)命令行工具,執(zhí)行命令 mkdir myapp && cd myapp;
  •  執(zhí)行命令npm create @umijs/umi-app創(chuàng)建一個(gè)React工程;
  •  執(zhí)行命令npm install安裝依賴;
  •  依賴安裝成功后,執(zhí)行命令npm run start啟動(dòng)項(xiàng)目,在瀏覽器上打開(kāi) http://localhost:8000 訪問(wèn)項(xiàng)目。

可以看見(jiàn)myapp這個(gè)React工程的目錄結(jié)構(gòu)如下所示:

 
 
 
  1. ├── package.json  
  2. ├── .umirc.ts  
  3. ├── .env  
  4. ├── dist  
  5. ├── mock  
  6. ├── public 
  7. └── src  
  8.     ├── .umi  
  9.     ├── layouts/index.tsx  
  10.     ├── pages  
  11.         ├── index.less  
  12.         └── index.tsx  
  13.     └── app.ts 

打開(kāi) .umirc.ts 文件,其內(nèi)容如下所示

 
 
 
  1. import { defineConfig } from 'umi';  
  2. export default defineConfig({  
  3.   nodeModulesTransform: {  
  4.     type: 'none',  
  5.   },  
  6.   routes: [  
  7.     { path: '/', component: '@/pages/index' },  
  8.   ],  
  9.   fastRefresh: {},  
  10. }); 

其路由是在routes選項(xiàng)中配置,配置和Vue Router非常相似,具體如何配置放在后面介紹路由跳轉(zhuǎn)和傳參中一并介紹。

接下來(lái)在_src/pages/index.tsx_文件中書寫demo來(lái)學(xué)習(xí)React。

2、React中如何開(kāi)發(fā)組件的UI

Vue和React中所開(kāi)發(fā)的都是組件,其頁(yè)面也是一個(gè)路由組件。在Vue中組件是定義在后綴為.vue的文件中,在React中組件是定義在后綴為.js的文件中,若使用TypeScript來(lái)開(kāi)發(fā)React,則其組件是定義在后綴為.tsx的文件中。

那如何開(kāi)發(fā)一個(gè)組件的UI部分,例如開(kāi)發(fā)一個(gè) HelloWorld 組件在瀏覽器頁(yè)面上展示hello world,一個(gè)組件的UI包括HTML部分和CSS部分。

2.1 HTML部分

組件的HTML部分,Vue推薦使用template模板,React推薦使用JSX語(yǔ)法。

在工程的_src/pages_文件夾中創(chuàng)建一個(gè)_HelloWorld.js_文件,在其中開(kāi)發(fā)HelloWorld組件。

此外React組件有兩種定義方法,一種是函數(shù)形式,一種是ES6的class形式。

函數(shù)形式,稱為函數(shù)組件:

 
 
 
  1. export default function HelloWorld() {  
  2.   return (  
  3.     
    hello world
      
  4.   );  

ES6的class形式,稱為類組件:

 
 
 
  1. import React from 'react';  
  2. export default class HelloWorld extends React.Component {  
  3.   constructor(props) {  
  4.     super(props);  
  5.   }  
  6.   render() {  
  7.     return (  
  8.       
    hello world
      
  9.     );  
  10.   }  

這里要注意函數(shù)名的首字母要大寫。在函數(shù)中的return后面用JSX語(yǔ)法來(lái)開(kāi)發(fā)組件的UI部分。

另外還要注意在return后面的內(nèi)容最外面要用()括起來(lái),否則在return同一行后面最少跟一個(gè)<才可以,如下所示:

 
 
 
  1. export default function HelloWorld() {  
  2.   return <  
  3.     div>hello world
  
  • 這樣看起來(lái)是不是怪怪的,所以最好加個(gè)()。

    2.2 綁定 Class 和 Style

    關(guān)于組件的CSS部分,其最重要的是綁定 Class 和 Style,才能給組件的HTML添加樣式。

    先來(lái)看一下 Class 與 Style 是固定不變,React 中是怎么綁定的。

     
     
     
    1. export default function HelloWorld() {  
    2.   return (  
    3.     
    4.       className="title head"  
    5.       style={{color:'red',fontSize:'16px'}}  
    6.     >  
    7.       hello world  
    8.     
      
  •   );  
  • React中是用className來(lái)綁定 Class,用style來(lái)綁定 Style。其中style接受的值是一個(gè)對(duì)象,且用{}中括號(hào)傳入,而且對(duì)象的屬性名只能用駝峰式 (camelCase) 來(lái)命名。

    在來(lái)看一下 Class 與 Style 是變量,在React中是怎么綁定的。

    •  類組件的寫法: 
     
     
     
    1. import React from 'react';  
    2. export default class HelloWorld extends React.Component {  
    3.   constructor(props) {  
    4.     super(props);  
    5.     this.state = {  
    6.       styleData: { color: 'red', 'fontSize': "16px" },  
    7.       isHead: true,  
    8.       className: 'title'  
    9.     };  
    10.   }  
    11.   render() {  
    12.     return (  
    13.       
    14.         className={`${this.state.className} ${this.state.isHead ? 'head' : ''}`}  
    15.         style={this.state.styleData}  
    16.       >  
    17.         hello world  
    18.       
      
  •     );  
  •   }  
    •  函數(shù)組件的寫法: 
     
     
     
    1. import { useState } from 'react';  
    2. export default function HelloWorld() {  
    3.   const [styleData] = useState({ color: 'red', 'fontSize': "16px" });  
    4.   const [isHead] = useState(true);  
    5.   const [className] = useState('title');  
    6.   return (  
    7.     
    8.       className={`${className} ${isHead ? 'head' : ''}`}  
    9.       style={styleData}  
    10.     >  
    11.       hello world  
    12.     
      
  •   );  
  • 在React中是使用{}給屬性賦值變量,且className只接受字符串,不接受數(shù)組或者對(duì)象,可以用ES6的模板字符串功能來(lái)拼接變量生成字符串。

    在函數(shù)組件的寫法中用useState這個(gè)React Hook定義了一些變量,useState的作用放在后面介紹。

    3、React中如何使用組件

    HelloWorld 組件寫好了,要如何使用呢?先回顧一下在Vue中是如何使用組件的,在使用組件前要先注冊(cè),可以注冊(cè)為全局組件或局部組件。

    在React中是沒(méi)有注冊(cè)組件的概念,因?yàn)榻M件相當(dāng)一個(gè)函數(shù),只有引入組件的概念,也沒(méi)有全局組件的概念。使用組件前必須用import先把組件引入并命名。

     
     
     
    1. import HelloWorld from './HelloWorld.js'  
    2. export default function Index(){  
    3.   return (  
    4.       
    5.   )  

    在React中組件的命名必須以大寫字母開(kāi)頭,因?yàn)?React 會(huì)將以小寫字母開(kāi)頭的組件視為原生 DOM 標(biāo)簽。

    4、React中如何定義組件數(shù)據(jù)

    從開(kāi)發(fā)Vue組件的經(jīng)驗(yàn)來(lái)說(shuō),一個(gè)組件的數(shù)據(jù),可以分為內(nèi)部數(shù)據(jù)和參數(shù)數(shù)據(jù)兩種。對(duì)于React也是如此,在React中把內(nèi)部數(shù)據(jù)稱為state,把參數(shù)數(shù)據(jù)稱為props。

    4.1 定義內(nèi)部數(shù)據(jù)state

    在上面介紹React中如何綁定變量形式的 Class 和 Style 的過(guò)程已經(jīng)定義了styleData、isHead、className這些內(nèi)部數(shù)據(jù)。

    •  在類組件中是在this.state這個(gè)對(duì)象中定義數(shù)據(jù): 
     
     
     
    1. this.state = {  
    2.   styleData: { color: 'red', 'fontSize': "16px" },  
    3.   isHead: true,  
    4.   className: 'title'  
    5. }; 
    •  在函數(shù)組件的寫法中使用useState這個(gè)React Hook定義了數(shù)據(jù): 
     
     
     
    1. const [styleData] = useState({ color: 'red', 'fontSize': "16px" });  
    2. const [isHead] = useState(true);  
    3. const [className] = useState('title'); 

    個(gè)人推薦使用函數(shù)形式來(lái)開(kāi)發(fā)React組件,可以使用React Hook,來(lái)避免去學(xué)習(xí) ES6 中 的 class 語(yǔ)法,還有煩人的this指向問(wèn)題,從而來(lái)降低入門難度。

    關(guān)于的React Hook 可以看https://zh-hans.reactjs.org/docs/hooks-intro.html" 。

    4.2 定義參數(shù)數(shù)據(jù)props

    props用來(lái)接收外部傳遞給組件的數(shù)據(jù)。例如在 HelloWorld 組件中定義title一個(gè)參數(shù)數(shù)據(jù)。

    •  類組件的寫法: 
     
     
     
    1. import React from 'react';  
    2. class HelloWorld extends React.Component {  
    3.   constructor(props) {  
    4.     super(props);  
    5.   }  
    6.   render() {  
    7.     return (  
    8.       
      {this.props.title}
        
    9.     );  
    10.   }  
    11. }  
    12. HelloWorld.defaultProps = {  
    13.   title: 'hello world'  
    14. };  
    15. export default HelloWorld; 

    在類組件中的構(gòu)造函數(shù)constructor接受props作為傳入組件的參數(shù)數(shù)據(jù)集合,并調(diào)用super(props)把props傳給React.Component構(gòu)造函數(shù),這樣類組件才能接受參數(shù)數(shù)據(jù)集合props,再用this.props.title來(lái)讀取title參數(shù)數(shù)據(jù)的值,另外可以用defaultProps來(lái)定義title參數(shù)數(shù)據(jù)的默認(rèn)值。

    •  函數(shù)組件的寫法: 
     
     
     
    1. import { useState } from 'react';  
    2. export default function HelloWorld(props) {  
    3.   const {title = 'hello world'} = props;  
    4.   return (  
    5.     
      {title}
        
    6.   );  

    函數(shù)組件接收一個(gè)props作為傳入組件參數(shù)數(shù)據(jù)的集合,利用 ES6 解構(gòu)賦值的功能,來(lái)獲取組件的參數(shù)數(shù)據(jù),并可以給參數(shù)數(shù)據(jù)設(shè)置默認(rèn)值。

    這里要注意了,在Vue的template模板中是用{{}}(雙大括號(hào))來(lái)使用數(shù)據(jù)的,而在React中是統(tǒng)一用{}(單大括號(hào))來(lái)使用數(shù)據(jù)的。

    參數(shù)數(shù)據(jù)Props是用接收外部傳遞給組件的數(shù)據(jù),那React中如何向組件傳遞數(shù)據(jù)呢?

    5、React中如何向組件傳遞數(shù)據(jù)

    在Vue中規(guī)定了動(dòng)態(tài)數(shù)據(jù)和字符串、數(shù)字、布爾值、數(shù)組、對(duì)象類型的靜態(tài)數(shù)據(jù)如何傳遞給組件,我們一一對(duì)應(yīng)去尋找React中如何傳遞。

    •  傳遞動(dòng)態(tài)數(shù)據(jù) 
     
     
     
    1. import { useState } from 'react';  
    2. import HelloWorld from './HelloWorld.js';  
    3. export default function Index(){  
    4.   const [styleData] = useState({ color: 'red', 'fontSize': "16px" });  
    5.   const [isHead] = useState(true);  
    6.   const [className] = useState('title');  
    7.   return (  
    8.     
    9.        styleData={styleData}   
    10.        isHead={isHead}   
    11.        className={className}  
    12.     />  
    13.   )  
    •  傳遞字符串類型的靜態(tài)數(shù)據(jù) 
     
     
     
    1.  
    •  傳遞數(shù)字類型的靜態(tài)數(shù)據(jù) 
     
     
     
    1.  
    •  傳遞布爾值類型的靜態(tài)數(shù)據(jù) 
     
     
     
    1.  
    •  傳遞數(shù)組類型的靜態(tài)數(shù)據(jù) 
     
     
     
    1.  
    •  傳遞對(duì)象類型的靜態(tài)數(shù)據(jù) 
     
     
     
    1.  

    可見(jiàn)在React中,除了傳遞字符串類型的靜態(tài)數(shù)據(jù),都要用{}包裹數(shù)據(jù)再賦值給組件標(biāo)簽上的屬性來(lái)傳遞數(shù)據(jù)給組件。

    6、React中如何監(jiān)聽(tīng)DOM事件

    6.1 監(jiān)聽(tīng)DOM元素的DOM事件

    •  類組件的寫法: 
     
     
     
    1. import React from 'react';  
    2. export default class HelloWorld extends React.Component {  
    3.   constructor(props) {  
    4.     super(props);  
    5.     // 為了在回調(diào)中使用 `this`,這個(gè)綁定是必不可少的  
    6.     thisthis.handleClick = this.handleClick.bind(this);  
    7.   }  
    8.   handleClick() {  
    9.     console.log('點(diǎn)擊事件');  
    10.   }  
    11.   render() {  
    12.     return (  
    13.       hello world
      
  •     );  
  •   }  
    •  函數(shù)組件的寫法: 
     
     
     
    1. export default function HelloWorld() {  
    2.   const handleClick = ()=>{  
    3.      console.log('點(diǎn)擊事件');  
    4.   }  
    5.   return (  
    6.     hello world
      
  •   );  
  • React中用onClick來(lái)監(jiān)聽(tīng)點(diǎn)擊事件,用{}包裹點(diǎn)擊事件觸發(fā)時(shí)執(zhí)行的函數(shù),再賦值給onClick。

    其中onClick是一個(gè)合成事件,在Vue中@后面跟著是DOM的原生事件,而React中on后面跟著并不是DOM的原生事件。例如Vue中監(jiān)聽(tīng)雙擊事件 @dblclick,而React中監(jiān)聽(tīng)雙擊事件 onDoubleClick。

    React中的合成事件具體可以看https://zh-hans.reactjs.org/docs/events.html#mouse-events。

    6.2 監(jiān)聽(tīng)React組件的DOM事件

    在Vue中用.native修飾符來(lái)監(jiān)聽(tīng)組件上的DOM事件,而在React中監(jiān)聽(tīng)組件上的DOM事件要這樣實(shí)現(xiàn)。

    例如在組件上監(jiān)聽(tīng)click事件,先要把click事件觸發(fā)時(shí)要執(zhí)行的函數(shù)當(dāng)作Props給組件傳遞進(jìn)去,在組件的根元素上監(jiān)聽(tīng)click事件,click事件觸發(fā)時(shí)執(zhí)行該P(yáng)rops,這樣來(lái)間接監(jiān)聽(tīng)組件上的click事件。具體實(shí)現(xiàn)如下所示:

    •  類組件的寫法: 
     
     
     
    1. import React from 'react';  
    2. export default class HelloWorld extends React.Component {  
    3.   constructor(props:any) {  
    4.     super(props);  
    5.     console.log(this.props)  
    6.     thisthis.handleClick = this.handleClick.bind(this);  
    7.   }  
    8.   handleClick() {  
    9.     this.props.onClick();  
    10.   }  
    11.   render() {  
    12.     return (  
    13.       hello world
      
  •     );  
  •   }  
  • }  
  •  
     
     
    1. import React from 'react';  
    2. import HelloWorld from './HelloWorld';  
    3. export default class Grandfather extends React.Component {  
    4.   handleClick() {  
    5.     console.log('點(diǎn)擊事件');  
    6.   }  
    7.   render() {  
    8.     return (  
    9.        { this.handleClick() }}>  
    10.         
    11.     )  
    12.   }  
    •  函數(shù)組件的寫法: 
     
     
     
    1. export default function HelloWorld(props) {  
    2.   const { onClick } = props  
    3.   const handleClick = () => {  
    4.     onClick();  
    5.   }  
    6.   return (  
    7.     hello world
      
  •   );  
  • }  
  •  
     
     
    1. import HelloWorld from './HelloWorld';  
    2. export default function Index(){  
    3.   const handleClick = ()=>{  
    4.     console.log('點(diǎn)擊事件');  
    5.   }  
    6.   return (  
    7.      { handleClick() }}>  
    8.       
    9.   )  

    7、React中組件如何改變數(shù)據(jù)

    上面介紹了,React組件的數(shù)據(jù)分為內(nèi)部數(shù)據(jù)state和參數(shù)數(shù)據(jù)props,對(duì)應(yīng)的改變方法也不一樣。

    7.1 改變內(nèi)部數(shù)據(jù)state

    比如要改變組件中定義的內(nèi)部數(shù)據(jù)title。

    •  類組件的寫法: 
     
     
     
    1. import React from 'react';  
    2. export default class HelloWorld extends React.Component {  
    3.   constructor(props) {  
    4.     super(props);  
    5.     this.state = {  
    6.       title: 'hello world', 
    7.       className: 'title'  
    8.     };  
    9.     // 為了在回調(diào)中使用 `this`,這個(gè)綁定是必不可少的  
    10.     thisthis.handleClick = this.handleClick.bind(this);  
    11.   } 
    12.    handleClick() {  
    13.     this.setState(state => ({  
    14.       title: 'hello react',  
    15.       className: 'title active'  
    16.     }));  
    17.   }   
    18.   render() {  
    19.     return (  
    20.       
    21.         className={className}  
    22.         onClick={this.handleClick}  
    23.       >{title}
      
  •     );  
  •   }  
  • 在this.setState()中可以傳遞一個(gè)函數(shù)或一個(gè)對(duì)象,建議傳遞一個(gè)函數(shù)(state,props) =>{},函數(shù)可以接受內(nèi)部數(shù)據(jù)state和參數(shù)數(shù)據(jù)props作為參數(shù),而且state和props只讀無(wú)法修改,每次調(diào)用this.setState時(shí)讀取到的state和Props都是最新,特別適用多次調(diào)用this.setState修改同一個(gè)state的場(chǎng)景。最后函數(shù)放回一個(gè)對(duì)象,對(duì)象的內(nèi)容為要修改的state。

    •  函數(shù)組件的寫法: 
     
     
     
    1. import { useState } from 'react';  
    2. export default function HelloWorld() {  
    3.   const [title,setTitle] = useState('hello world');  
    4.   const [className,setClassName] = useState('title');  
    5.   const handleClick = () =>{  
    6.     setTitle('hello react');  
    7.     setClassName('title active')  
    8.   }  
    9.   return (  
    10.     
    11.       className={className}   
    12.       onClick={handleClick}  
    13.     >  
    14.       {title}  
    15.     
      
  •   );  
  • 在React中稱內(nèi)部數(shù)據(jù)為state,使用useState(param)定義一個(gè)state時(shí),可以通過(guò)參數(shù)param設(shè)置state的默認(rèn)值,其返回一個(gè)數(shù)組,數(shù)組的第一個(gè)值是state,數(shù)組的第二個(gè)值是改變state的函數(shù),可以調(diào)用該函數(shù)來(lái)改變state。

    另外用useState定義的數(shù)據(jù)是響應(yīng)式的,若頁(yè)面有使用該數(shù)據(jù),該數(shù)據(jù)改變后頁(yè)面會(huì)重新渲染。

    7.2 改變參數(shù)數(shù)據(jù)props

    跟Vue一樣,在組件中是不能直接改變props,假如要改變props,只能通過(guò)在父組件中改變傳遞給子組件的數(shù)據(jù)來(lái)間接改變props,那在子組件中怎么讓父組件改變傳遞給子組件的數(shù)據(jù)呢,將在React中父子組件如何通訊介紹。

    8、React中父子組件如何通訊

    用一個(gè)例子來(lái)介紹,假如 HelloWorld 組件的 “hello world” 是用參數(shù)數(shù)據(jù)props中的title展示,點(diǎn)擊組件中的改變標(biāo)題按鈕時(shí)變成 “hello React” 。

     
     
     
    1. import React from 'react';  
    2. class HelloWorld extends React.Component {  
    3.   constructor(props) {  
    4.     super(props);  
    5.     thisthis.handleChangeTitle=this.handleChangeTitle.bind(this);  
    6.   }  
    7.   handleChangeTitle(){  
    8.     this.props.changeTitle('hello React');  
    9.   }  
    10.   render() {  
    11.     return (  
    12.       
        
    13.         {this.props.title}  
    14.         
    15.           onClick={this.handleChangeTitle.bind(this)}>  
    16.           改變標(biāo)題  
    17.           
    18.       
      
  •     );  
  •   }  
  • }  
  • HelloWorld.defaultProps = {  
  •   title: 'hello world'  
  • };  
  • export default HelloWorld;  
  •  
     
     
    1. import HelloWorld from './HelloWorld.js'  
    2. import React from 'react'  
    3. class Index extends React.Component {  
    4.   constructor(props) {  
    5.     super(props);  
    6.     this.state={  
    7.       info:'hello world'  
    8.     };  
    9.     thisthis.handleChangeTitle=this.handleChangeTitle.bind(this);  
    10.   }  
    11.   handleChangeTitle(data){  
    12.     this.setState(state =>{  
    13.       return {  
    14.         info:data  
    15.       }  
    16.     })  
    17.   }  
    18.   render() {  
    19.     return (  
    20.       
    21.         title={this.state.info}   
    22.         changeTitle={this.handleChangeTitle}>  
    23.         
    24.     );  
    25.   }  
    26. }  
    27. export default Index; 
     
     
     
    1. export default function HelloWorld(props: any) { 
    2.   const { title = 'hello world', changeTitle } = props;  
    3.   const handleChangeTitle = () => {  
    4.     changeTitle('hello React')  
    5.   }  
    6.   return (  
    7.     
        
    8.       {title}  
    9.       改變標(biāo)題  
    10.     
      
  •   );  
  • }  
  •  
     
     
    1. import { useState } from 'react'  
    2. import HelloWorld from './HelloWorld.js'  
    3. export default function Index(){  
    4.   const [info,setInfo] = useState('hello world');  
    5.   const handleChangeTitle = (data)=>{  
    6.     setInfo(data);  
    7.   }  
    8.   return (  
    9.       
    10.   )  

    在父組件中定義一個(gè)info數(shù)據(jù)傳遞給子組件的title參數(shù)數(shù)據(jù),同時(shí)也定義了一個(gè)回調(diào)函數(shù)handleChangeTitle來(lái)改變info數(shù)據(jù),并把回調(diào)函數(shù)也傳遞給子組件的changeTitle參數(shù)數(shù)據(jù)。

    這樣子組件的changeTitle參數(shù)數(shù)據(jù)可以作為一個(gè)函數(shù)來(lái)調(diào)用,調(diào)用changeTitle時(shí)相當(dāng)調(diào)用handleChangeTitle回調(diào)函數(shù),可以把要改變的值通過(guò)data函數(shù)參數(shù)傳遞出來(lái),再執(zhí)行setInfo(data)改變info數(shù)據(jù),再傳遞給子組件的title參數(shù)數(shù)據(jù),間接改變了title參數(shù)數(shù)據(jù),實(shí)現(xiàn)了React中組件如何改變參數(shù)數(shù)據(jù)。

    在父組件中也可以調(diào)用setInfo改變傳遞給子組件的title參數(shù)數(shù)據(jù)的info數(shù)據(jù),以上就是React中父子組件通訊的一個(gè)方法。

    9、React中如何監(jiān)聽(tīng)組件數(shù)據(jù)的變化

    在Vue中可以用簡(jiǎn)單地用watch來(lái)監(jiān)聽(tīng)數(shù)據(jù)的變化,而在React中比較復(fù)雜,子組件的類型不同實(shí)現(xiàn)方法也不同。

    在類組件中用componentDidUpdate這個(gè)生命周期方法來(lái)實(shí)現(xiàn),該方法首次渲染時(shí)componentDidUpdate不會(huì)執(zhí)行,在后續(xù)props和state改變時(shí)會(huì)觸發(fā)componentDidUpdate,其接受的第一個(gè)參數(shù)prevProps代表改變前的props,第二參數(shù)prevState代表改變前的state。

     
     
     
    1. componentDidUpdate(prevProps, prevState){  
    2.   if(prevProps.title !== this.props.title){  
    3.      console.log('props中的title數(shù)據(jù)改變了');  
    4.   }  
    5.   if(prevState.info !== this.state.info){  
    6.      console.log('state中的info數(shù)據(jù)改變了');  
    7.   }  

    在函數(shù)組件中,可以u(píng)seEffect這個(gè)React Hook監(jiān)聽(tīng)數(shù)據(jù)的變化,但是無(wú)法像Vue的watch能夠獲取改變前的舊數(shù)據(jù)。所以要自定義一個(gè)Hook來(lái)實(shí)現(xiàn)類似Vue的watch的功能。自定義Hook是一個(gè)函數(shù),其名稱以 “use” 開(kāi)頭,函數(shù)內(nèi)部可以調(diào)用其他的 Hook。故把這個(gè)自定義Hook稱為useWatch。

    如何獲取改變前的舊數(shù)據(jù),可以在第一次數(shù)據(jù)改變時(shí)觸發(fā)useWatch時(shí)用一個(gè)容器把舊數(shù)據(jù)存儲(chǔ)起來(lái),下次再觸發(fā)useWatch時(shí)通過(guò)讀取容器中的值就可以獲取改變前的舊數(shù)據(jù)。容器可以用useRef這個(gè) Hook 來(lái)創(chuàng)建。

    useRef 返回一個(gè)可變的 ref 對(duì)象,其 .current 屬性被初始化為傳入的參數(shù)(initialValue)。返回的 ref 對(duì)象在組件的整個(gè)生命周期內(nèi)保持不變。

     
     
     
    1. import {useEffect,useRef} from 'react';  
    2. export function useWatch(value,callback){  
    3.   const oldValue = useRef();  
    4.   useEffect(() =>{  
    5.     callback(value,oldValue.current);  
    6.     oldValue.current=value;  
    7.   },[value])  

    但是useEffect會(huì)在組件初次渲染后就會(huì)調(diào)用一次,導(dǎo)致callback回調(diào)函數(shù)會(huì)被執(zhí)行一次,另外在Vue的watch是用immediate配置來(lái)控制在組件初次渲染后馬上執(zhí)行callback回調(diào)函數(shù),且默認(rèn)不會(huì)在組件初次渲染后執(zhí)行callback回調(diào)函數(shù),接著在_hook.js_中定義一個(gè)useWatch。

    首先實(shí)現(xiàn)一下組件初次渲染不執(zhí)行callback回調(diào)函數(shù)。

     
     
     
    1. import {useEffect,useRef} from 'react';  
    2. export function useWatch(value,callback){  
    3.   const oldValue = useRef();  
    4.   const isInit = useRef(false);  
    5.   useEffect(() =>{  
    6.     if(!isInit.current){  
    7.       isInit.current = true;  
    8.     }else{  
    9.       callback(value,oldValue.current);  
    10.     } 
    11.     oldValue.current=value;  
    12.   },[value])  

    再添加immediate配置來(lái)控制在組件初次渲染后是否馬上執(zhí)行callback回調(diào)函數(shù)。

     
     
     
    1. import {useEffect,useRef} from 'react';  
    2. export function useWatch(value,callback,config={immediate: false}){  
    3.   const oldValue = useRef();  
    4.   const isInit = useRef(false);  
    5.   useEffect(() =>{  
    6.     if(!isInit.current){  
    7.       isInit.current = true;  
    8.       if(config.immediate){  
    9.         callback(value,oldValue.current);  
    10.       }  
    11.     }else{  
    12.       callback(value,oldValue.current);  
    13.     } 
    14.     oldValue.current=value;  
    15.   },[value])  

    另外Vue的watch還返回一個(gè)unwatch函數(shù),調(diào)用unwatch函數(shù)可以停止監(jiān)聽(tīng)該數(shù)據(jù)。

     
     
     
    1. import { useEffect, useRef } from 'react';  
    2. export function useWatch(value, callback, config = { immediate: false }) {  
    3.   const oldValue = useRef();  
    4.   const isInit = useRef(false);  
    5.   const isWatch = useRef(true);  
    6.   useEffect(() => {  
    7.     if (isWatch.current) {  
    8.       if (!isInit.current) {  
    9.         isInit.current = true;  
    10.         if (config.immediate) {  
    11.           callback(value, oldValue.current);  
    12.         }  
    13.       } else {  
    14.         callback(value, oldValue.current);  
    15.       }  
    16.       oldValue.current = value;  
    17.     }  
    18.   }, [value])  
    19.   const unwatch =  () => {  
    20.     isWatch.current = false;  
    21.   };  
    22.   return unwatch;  
    23. }  
     
     
     
    1. useWatch 這個(gè)Hook 定義好后,這么使用。  
    2. export {useState} from 'react';  
    3. export {useWatch} from './hook.js';  
    4. export default function HelloWorld() {  
    5.   const [title,setTitle] = useState('hello world')  
    6.   useWatch(title, (value, oldValue) => {  
    7.     console.log(value);  
    8.     console.log(oldValue)  
    9.   })  
    10.   const handleChangeTitle = () => {  
    11.     setTitle('hello React')  
    12.   }  
    13.   return (  
    14.     {title}  
    15.   );  

    10、React中父組件如何調(diào)用子組件的方法

    在Vue中是使用ref給子組件賦予一個(gè)標(biāo)識(shí) ID ,再使用this.$refs[ID]訪問(wèn)到這個(gè)子組件的實(shí)例對(duì)象,然后通過(guò)實(shí)例對(duì)象去調(diào)用子組件的方法。而在React中比較復(fù)雜,子組件的類型不同實(shí)現(xiàn)方法也不同。

     
     
     
    1. import React from 'react';  
    2. export default class HelloWorld extends React.Component {  
    3.   constructor(props) {  
    4.     super(props);  
    5.     this.state = {  
    6.       title:'hello World'  
    7.     };  
    8.   }  
    9.   handleChangeTitle(){ 
    10.     this.setState({  
    11.       title:'hello React'  
    12.     });  
    13.   }  
    14.   render() {  
    15.     return (  
    16.       
        
    17.         {this.state.title}  
    18.         
    19.     );  
    20.   }  
    21. }  
     
     
     
    1. import React from 'react';  
    2. import HelloWorld from './HelloWorld.js';  
    3. class Index extends React.Component {  
    4.   constructor(props) {  
    5.     super(props)  
    6.     this.myCom = React.createRef();  

    7. 當(dāng)前文章:從 Vue2.0 到 React17 —— React 開(kāi)發(fā)入門
      轉(zhuǎn)載源于:http://www.dlmjj.cn/article/ccchpph.html