從Vue2.0到React17——React開發(fā)入門

前言

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

前端項(xiàng)目是由一個(gè)個(gè)頁面組成的,對(duì)于Vue來說,一個(gè)頁面是由多個(gè)組件構(gòu)成的谍夭,頁面本身也是一個(gè)路由組件黑滴。對(duì)于React來說也是如此。Vue會(huì)提供一系列技術(shù)支持來完成一個(gè)組件的開發(fā)紧索,可以從這一系列技術(shù)支持出發(fā)袁辈,去React中尋找對(duì)應(yīng)的技術(shù)支持來入門React,比如React中如何開發(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工程椎侠,步驟很簡單:

  • 先找個(gè)地方建個(gè)空目錄,打開命令行工具措拇,執(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)目,在瀏覽器上打開 http://localhost:8000 訪問項(xiàng)目券犁。

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

.
├── package.json
├── .umirc.ts
├── .env
├── dist
├── mock
├── public
└── src
    ├── .umi
    ├── layouts/index.tsx
    ├── pages
        ├── index.less
        └── index.tsx
    └── app.ts
復(fù)制代碼

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

import { defineConfig } from 'umi';

export default defineConfig({
  nodeModulesTransform: {
    type: 'none',
  },
  routes: [
    { path: '/', component: '@/pages/index' },
  ],
  fastRefresh: {},
});
復(fù)制代碼

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

接下來在src/pages/index.tsx文件中書寫demo來學(xué)習(xí)React。

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

Vue和React中所開發(fā)的都是組件勘伺,其頁面也是一個(gè)路由組件。在Vue中組件是定義在后綴為.vue的文件中褂删,在React中組件是定義在后綴為.js的文件中飞醉,若使用TypeScript來開發(fā)React,則其組件是定義在后綴為.tsx的文件中屯阀。

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

2.1 HTML部分

組件的HTML部分钦无,Vue推薦使用template模板逗栽,React推薦使用JSX語法。

在工程的src/pages文件夾中創(chuàng)建一個(gè)HelloWorld.js文件铃诬,在其中開發(fā)HelloWorld組件祭陷。

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

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

export default function HelloWorld() {
  return (
    <div>hello world</div>
  );
}
復(fù)制代碼

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

import React from 'react';
export default class HelloWorld extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <div>hello world</div>
    );
  }
}
復(fù)制代碼

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

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

export default function HelloWorld() {
  return <
    div>hello world</div>
}
復(fù)制代碼

這樣看起來是不是怪怪的,所以最好加個(gè)()笙瑟。

2.2 綁定 Class 和 Style

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

先來看一下 Class 與 Style 是固定不變框产,React 中是怎么綁定的。

export default function HelloWorld() {
  return (
    <div 
      className="title head"
      style={{color:'red',fontSize:'16px'}}
    >
      hello world
    </div>
  );
}
復(fù)制代碼

React中是用className來綁定 Class错洁,用style來綁定 Style秉宿。其中style接受的值是一個(gè)對(duì)象,且用{}中括號(hào)傳入屯碴,而且對(duì)象的屬性名只能用駝峰式 (camelCase) 來命名描睦。

在來看一下 Class 與 Style 是變量,在React中是怎么綁定的导而。

  • 類組件的寫法:
import React from 'react';
export default class HelloWorld extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      styleData: { color: 'red', 'fontSize': "16px" },
      isHead: true,
      className: 'title'
    };
  }

  render() {
    return (
      <div
        className={`${this.state.className} ${this.state.isHead ? 'head' : ''}`}
        style={this.state.styleData}
      >
        hello world
      </div>
    );
  }
}
復(fù)制代碼
  • 函數(shù)組件的寫法:
import { useState } from 'react';
export default function HelloWorld() {
  const [styleData] = useState({ color: 'red', 'fontSize': "16px" });
  const [isHead] = useState(true);
  const [className] = useState('title');
  return (
    <div
      className={`${className} ${isHead ? 'head' : ''}`}
      style={styleData}
    >
      hello world
    </div>
  );
}
復(fù)制代碼

在React中是使用{}給屬性賦值變量忱叭,且className只接受字符串,不接受數(shù)組或者對(duì)象今艺,可以用ES6的模板字符串功能來拼接變量生成字符串窑多。

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

3埂息、React中如何使用組件

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

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

import HelloWorld from './HelloWorld.js'

export default function Index(){
  return (
    <HelloWorld/>
  )
}
復(fù)制代碼

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

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

從開發(fā)Vue組件的經(jīng)驗(yàn)來說,一個(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 的過程已經(jīng)定義了styleDataisHead跟畅、className這些內(nèi)部數(shù)據(jù)咽筋。

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

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

關(guān)于的React Hook 可以看這里

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

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

  • 類組件的寫法:
import React from 'react';
class HelloWorld extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <div>{this.props.title}</div>
    );
  }
}
HelloWorld.defaultProps = {
  title: 'hello world'
};
export default HelloWorld;
復(fù)制代碼

在類組件中的構(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來讀取title參數(shù)數(shù)據(jù)的值,另外可以用defaultProps來定義title參數(shù)數(shù)據(jù)的默認(rèn)值晃酒。

  • 函數(shù)組件的寫法:
import { useState } from 'react';
export default function HelloWorld(props) {
  const {title = 'hello world'} = props;
  return (
    <div>{title}</div>
  );
}
復(fù)制代碼

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

這里要注意了,在Vue的template模板中是用{{}}(雙大括號(hào))來使用數(shù)據(jù)的,而在React中是統(tǒng)一用{}(單大括號(hào))來使用數(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ù)
import { useState } from 'react';
import HelloWorld from './HelloWorld.js';
export default function Index(){
  const [styleData] = useState({ color: 'red', 'fontSize': "16px" });
  const [isHead] = useState(true);
  const [className] = useState('title');
  return (
    <HelloWorld 
       styleData={styleData} 
       isHead={isHead} 
       className={className}
    />
  )
}
復(fù)制代碼
  • 傳遞字符串類型的靜態(tài)數(shù)據(jù)
<HelloWorld title="hello vue"></HelloWorld>
復(fù)制代碼
  • 傳遞數(shù)字類型的靜態(tài)數(shù)據(jù)
<HelloWorld num={1}></HelloWorld>
復(fù)制代碼
  • 傳遞布爾值類型的靜態(tài)數(shù)據(jù)
<HelloWorld isHead={false}></HelloWorld>
復(fù)制代碼
  • 傳遞數(shù)組類型的靜態(tài)數(shù)據(jù)
<HelloWorld className={['title','head']}></HelloWorld>
復(fù)制代碼
  • 傳遞對(duì)象類型的靜態(tài)數(shù)據(jù)
<HelloWorld styleData={{color:'red','fontSize':"16px"}}></HelloWorld>
復(fù)制代碼

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

6组哩、React中如何監(jiān)聽DOM事件

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

  • 類組件的寫法:
import React from 'react';
export default class HelloWorld extends React.Component {
  constructor(props) {
    super(props);
    // 為了在回調(diào)中使用 `this`,這個(gè)綁定是必不可少的
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    console.log('點(diǎn)擊事件');
  }

  render() {
    return (
      <div onClick={this.handleClick}>hello world</div>
    );
  }
}
復(fù)制代碼
  • 函數(shù)組件的寫法:
export default function HelloWorld() {
  const handleClick = ()=>{
     console.log('點(diǎn)擊事件');
  }
  return (
    <div onClick={handleClick}>hello world</div>
  );
}
復(fù)制代碼

React中用onClick來監(jiān)聽點(diǎn)擊事件处渣,用{}包裹點(diǎn)擊事件觸發(fā)時(shí)執(zhí)行的函數(shù)伶贰,再賦值給onClick

其中onClick是一個(gè)合成事件罐栈,在Vue中@后面跟著是DOM的原生事件黍衙,而React中on后面跟著并不是DOM的原生事件。例如Vue中監(jiān)聽雙擊事件 @dblclick荠诬,而React中監(jiān)聽雙擊事件 onDoubleClick琅翻。

React中的合成事件具體可以看這里

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

在Vue中用.native修飾符來監(jiān)聽組件上的DOM事件柑贞,而在React中監(jiān)聽組件上的DOM事件要這樣實(shí)現(xiàn)方椎。

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

  • 類組件的寫法:
import React from 'react';
export default class HelloWorld extends React.Component {
  constructor(props:any) {
    super(props);
    console.log(this.props)
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.props.onClick();
  }

  render() {
    return (
      <div onClick={this.handleClick}>hello world</div>
    );
  }
}
復(fù)制代碼
import React from 'react';
import HelloWorld from './HelloWorld';
export default class Grandfather extends React.Component {
  handleClick() {
    console.log('點(diǎn)擊事件');
  }
  render() {
    return (
      <HelloWorld onClick={() => { this.handleClick() }}>
      </HelloWorld>
    )
  }
}
復(fù)制代碼
  • 函數(shù)組件的寫法:
export default function HelloWorld(props) {
  const { onClick } = props
  const handleClick = () => {
    onClick();
  }
  return (
    <div onClick={handleClick}>hello world</div>
  );
}
復(fù)制代碼
import HelloWorld from './HelloWorld';
export default function Index(){
  const handleClick = ()=>{
    console.log('點(diǎn)擊事件');
  }
  return (
    <HelloWorld onClick={() => { handleClick() }}>
    </HelloWorld>
  )
}
復(fù)制代碼

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

  • 類組件的寫法:
import React from 'react';
export default class HelloWorld extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      title: 'hello world',
      className: 'title'
    };
    // 為了在回調(diào)中使用 `this`台汇,這個(gè)綁定是必不可少的
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState(state => ({
      title: 'hello react',
      className: 'title active'
    }));
  }

  render() {
    return (
      <div 
        className={className}
        onClick={this.handleClick}
      >{title}</div>
    );
  }
}
復(fù)制代碼

this.setState()中可以傳遞一個(gè)函數(shù)或一個(gè)對(duì)象苛骨,建議傳遞一個(gè)函數(shù)(state,props) =>{}篱瞎,函數(shù)可以接受內(nèi)部數(shù)據(jù)state和參數(shù)數(shù)據(jù)props作為參數(shù),而且stateprops只讀無法修改智袭,每次調(diào)用this.setState時(shí)讀取到的state和Props都是最新奔缠,特別適用多次調(diào)用this.setState修改同一個(gè)state的場(chǎng)景。最后函數(shù)放回一個(gè)對(duì)象吼野,對(duì)象的內(nèi)容為要修改的state校哎。

  • 函數(shù)組件的寫法:
import { useState } from 'react';
export default function HelloWorld() {
  const [title,setTitle] = useState('hello world');
  const [className,setClassName] = useState('title');
  const handleClick = () =>{
    setTitle('hello react');
    setClassName('title active')
  }
  return (
    <div 
      className={className} 
      onClick={handleClick}
    >
      {title}
    </div>
  );
}
復(fù)制代碼

在React中稱內(nèi)部數(shù)據(jù)為state,使用useState(param)定義一個(gè)state時(shí)瞳步,可以通過參數(shù)param設(shè)置state的默認(rèn)值闷哆,其返回一個(gè)數(shù)組,數(shù)組的第一個(gè)值是state单起,數(shù)組的第二個(gè)值是改變state的函數(shù)抱怔,可以調(diào)用該函數(shù)來改變state。

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

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

跟Vue一樣测蘑,在組件中是不能直接改變props灌危,假如要改變props,只能通過在父組件中改變傳遞給子組件的數(shù)據(jù)來間接改變props碳胳,那在子組件中怎么讓父組件改變傳遞給子組件的數(shù)據(jù)呢勇蝙,將在React中父子組件如何通訊介紹。

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

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

  • 類組件的寫法:
import React from 'react';
class HelloWorld extends React.Component {
  constructor(props) {
    super(props);
    this.handleChangeTitle=this.handleChangeTitle.bind(this);
  }
  handleChangeTitle(){
    this.props.changeTitle('hello React');
  }
  render() {
    return (
      <div>
        {this.props.title}
        <button 
          onClick={this.handleChangeTitle.bind(this)}>
          改變標(biāo)題
        </button>
      </div>
    );
  }
}
HelloWorld.defaultProps = {
  title: 'hello world'
};
export default HelloWorld;
復(fù)制代碼
import HelloWorld from './HelloWorld.js'
import React from 'react'
class Index extends React.Component {
  constructor(props) {
    super(props);
    this.state={
      info:'hello world'
    };
    this.handleChangeTitle=this.handleChangeTitle.bind(this);
  }
  handleChangeTitle(data){
    this.setState(state =>{
      return {
        info:data
      }
    })
  }
  render() {
    return (
      <HelloWorld 
        title={this.state.info} 
        changeTitle={this.handleChangeTitle}>
      </HelloWorld>
    );
  }
}
export default Index;
復(fù)制代碼
  • 函數(shù)組件的寫法:
export default function HelloWorld(props: any) {
  const { title = 'hello world', changeTitle } = props;
  const handleChangeTitle = () => {
    changeTitle('hello React')
  }
  return (
    <div>
      {title}
      <button onClick={handleChangeTitle}>改變標(biāo)題</button>
    </div>
  );
}
復(fù)制代碼
import { useState } from 'react'
import HelloWorld from './HelloWorld.js'

export default function Index(){
  const [info,setInfo] = useState('hello world');
  const handleChangeTitle = (data)=>{
    setInfo(data);
  }
  return (
    <HelloWorld title={info} changeTitle={handleChangeTitle}/>
  )
}
復(fù)制代碼

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

這樣子組件的changeTitle參數(shù)數(shù)據(jù)可以作為一個(gè)函數(shù)來調(diào)用馆衔,調(diào)用changeTitle時(shí)相當(dāng)調(diào)用handleChangeTitle回調(diào)函數(shù),可以把要改變的值通過data函數(shù)參數(shù)傳遞出來隘弊,再執(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)聽組件數(shù)據(jù)的變化

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

  • 類組件的寫法:

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

componentDidUpdate(prevProps, prevState){
  if(prevProps.title !== this.props.title){
     console.log('props中的title數(shù)據(jù)改變了');
  }
  if(prevState.info !== this.state.info){
     console.log('state中的info數(shù)據(jù)改變了');
  }
}
復(fù)制代碼
  • 函數(shù)組件的寫法

在函數(shù)組件中绊袋,可以useEffect這個(gè)React Hook監(jiān)聽數(shù)據(jù)的變化,但是無法像Vue的watch能夠獲取改變前的舊數(shù)據(jù)铸鹰。所以要自定義一個(gè)Hook來實(shí)現(xiàn)類似Vue的watch的功能癌别。自定義Hook是一個(gè)函數(shù),其名稱以 “use” 開頭蹋笼,函數(shù)內(nèi)部可以調(diào)用其他的 Hook展姐。故把這個(gè)自定義Hook稱為useWatch

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

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

import {useEffect,useRef} from 'react';
export function useWatch(value,callback){
  const oldValue = useRef();
  useEffect(() =>{
    callback(value,oldValue.current);
    oldValue.current=value;
  },[value])
}
復(fù)制代碼

但是useEffect會(huì)在組件初次渲染后就會(huì)調(diào)用一次谍婉,導(dǎo)致callback回調(diào)函數(shù)會(huì)被執(zhí)行一次,另外在Vue的watch是用immediate配置來控制在組件初次渲染后馬上執(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ù)丁溅。

import {useEffect,useRef} from 'react';
export function useWatch(value,callback){
  const oldValue = useRef();
  const isInit = useRef(false);
  useEffect(() =>{
    if(!isInit.current){
      isInit.current = true;
    }else{
      callback(value,oldValue.current);
    }
    oldValue.current=value;
  },[value])
}
復(fù)制代碼

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

import {useEffect,useRef} from 'react';
export function useWatch(value,callback,config={immediate: false}){
  const oldValue = useRef();
  const isInit = useRef(false);
  useEffect(() =>{
    if(!isInit.current){
      isInit.current = true;
      if(config.immediate){
        callback(value,oldValue.current);
      }
    }else{
      callback(value,oldValue.current);
    }
    oldValue.current=value;
  },[value])
}
復(fù)制代碼

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

import { useEffect, useRef } from 'react';
export function useWatch(value, callback, config = { immediate: false }) {
  const oldValue = useRef();
  const isInit = useRef(false);
  const isWatch = useRef(true);
  useEffect(() => {
    if (isWatch.current) {
      if (!isInit.current) {
        isInit.current = true;
        if (config.immediate) {
          callback(value, oldValue.current);
        }
      } else {
        callback(value, oldValue.current);
      }
      oldValue.current = value;
    }
  }, [value])

  const unwatch =  () => {
    isWatch.current = false;
  };
  return unwatch;
}
復(fù)制代碼

useWatch 這個(gè)Hook 定義好后妓柜,這么使用。

export {useState} from 'react';
export {useWatch} from './hook.js';
export default function HelloWorld() {
  const [title,setTitle] = useState('hello world')
  useWatch(title, (value, oldValue) => {
    console.log(value);
    console.log(oldValue)
  })
  const handleChangeTitle = () => {
    setTitle('hello React')
  }
  return (
    <div onClick={handleChangeTitle}>{title}</div>
  );
}
復(fù)制代碼

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

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

  • 類子組件的寫法:
import React from 'react';
export default class HelloWorld extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      title:'hello World'
    };
  }
  handleChangeTitle(){
    this.setState({
      title:'hello React'
    });
  }
  render() {
    return (
      <div>
        {this.state.title}
      </div>
    );
  }
}
復(fù)制代碼
import React from 'react';
import HelloWorld from './HelloWorld.js';

class Index extends React.Component {
  constructor(props) {
    super(props)
    this.myCom = React.createRef();
    this.changeTitle = this.changeTitle.bind(this);
  }
  changeTitle() {
    this.myCom.current.handleChangeTitle();
  }
  render() {
    return (
      <div>
        <HelloWorld ref={this.myCom} />
        <button onClick={this.changeTitle}>改變標(biāo)題</button>
      </div>
    )
  }
}
export default Index;
復(fù)制代碼
  • 函數(shù)組件的寫法:

useRef()無法使用在函數(shù)組件上使用,在函數(shù)組件中要先使用 useImperativeHandle 定義要暴露給父組件的實(shí)例值粟誓,另外要把函數(shù)組件傳入forwardRef處理后再導(dǎo)出奏寨。

import { useState, forwardRef, useImperativeHandle } from 'react';

const HelloWorld = (props, ref) => {
  const [title, setTitle] = useState('hello World');
  useImperativeHandle(ref, () => ({
    handleChangeTitle: () => {
      setTitle('hello React')
    },
  }));
  return (
    <div>{title}</div>
  );
}
export default forwardRef(HelloWorld)
復(fù)制代碼
import { useRef } from 'react'
import HelloWorld from './HelloWorld.js'

export default function Index() {
  const myCom = useRef();
  const changeTitle = () => {
    myCom.current.handleChangeTitle();
  }
  return (
    <div>
      <HelloWorld ref={myCom} />
      <button onClick={changeTitle}>改變標(biāo)題</button>
    </div>
  )
}
復(fù)制代碼

11、React中組件插槽怎么實(shí)現(xiàn)

11.1 普通插槽

其實(shí)React中是沒有插槽的概念,不過可以用props.children來實(shí)現(xiàn)插槽的功能。

每個(gè)組件都可以獲取到 props.children陆赋。它包含組件的開始標(biāo)簽和結(jié)束標(biāo)簽之間的內(nèi)容局义。

例如開發(fā)一個(gè) HelloWorld 組件用來展示 “ hello World ” ,也可以用插槽的形式來實(shí)現(xiàn),通過props.children把 “ hello World ” 從父組件傳遞進(jìn)去。

類組件的寫法:

import React from 'react';
export default class HelloWorld extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div>
        {this.props.children}
      </div>
    );
  }
}
復(fù)制代碼
import React from 'react';
import HelloWorld from './HelloWorld.js';
class Index extends React.Component{
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <HelloWorld>hello World</HelloWorld>
    )
  }
}
export default Index;
復(fù)制代碼

函數(shù)組件的寫法:

export default function HelloWorld(props){
  const {children}=props;
  return (
    <div>
      {children}
    </div>
  );
}
復(fù)制代碼
import HelloWorld from './HelloWorld.js';
export default function Index(){
  return (
    <HelloWorld>hello World</HelloWorld>
  )
}
復(fù)制代碼

11.2 具名插槽

可以通過props給子組件傳遞一個(gè)函數(shù),如果這個(gè)函數(shù)最后返回React元素笼踩,其React元素是用JSX語法編寫的,這樣就間接實(shí)現(xiàn)具名插槽的功能亡嫌。

例如開發(fā)一個(gè) HelloWorld 組件用來展示 “ hello World ” 嚎于,用具名插槽的形式來實(shí)現(xiàn)。

類組件的寫法:

import React from 'react';
class HelloWorld extends React.Component{
  constructor(props){
    super(props)
    this.elementSlot = "";
    if (this.props.element) {
      this.elementSlot = this.props.element();
    }
  }
  render(){
    return (
      <div>
        {this.elementSlot}
      </div>
    );
  }
}
export default HelloWorld;
復(fù)制代碼
import React from 'react';
import HelloWorld from './HelloWorld.js';
class Index extends React.Component{
  constructor(props) {
    super(props);
  }
  info(){
    return(
      <span>hello World</span>
    )
  }
  render() {
    return (
      <HelloWorld element={this.info}></HelloWorld>
    )
  }
}
export default Index;
復(fù)制代碼

函數(shù)組件的寫法:

export default function HelloWorld(props) {
  const { children, element } = props;
  let elementSlot = "";
  if (element) {
    elementSlot = element();
  }
  return (
    <div>
      {elementSlot}
    </div>
  );
}
復(fù)制代碼
import HelloWorld from './HelloWorld.js';

export default function Index(){
  const info = () =>{
    return (
      <span>hello World</span>
    )
  }
  return (
    <HelloWorld element={info}></HelloWorld>
  )
}
復(fù)制代碼

11.3 作用域插槽

Vue的作用域插槽的作用是用子組件中的數(shù)據(jù)在父組件中寫插槽內(nèi)容挟冠。

回顧上面具名插槽的實(shí)現(xiàn)過程于购,先在父組件中定義一個(gè)函數(shù),該函數(shù)能返回一個(gè)React元素知染,再通過props把該函數(shù)傳遞給子組件肋僧,在子組件中執(zhí)行該函數(shù),把執(zhí)行結(jié)果添加到子組件的React元素中控淡。

如果在子組件中執(zhí)行該函數(shù)時(shí)嫌吠,把子組件的數(shù)據(jù)當(dāng)作參數(shù)傳遞進(jìn)去,那么在父組件中就可以用該函數(shù)接收子組件的數(shù)據(jù)來寫React元素(插槽的內(nèi)容)掺炭。這樣就實(shí)現(xiàn)了作用域插槽辫诅。

例如開發(fā)一個(gè) HelloWorld 組件用來展示 “ 用子組件的數(shù)據(jù)寫具名插槽 hello World ” ,用作用域插槽的形式來實(shí)現(xiàn)涧狮。

類組件的寫法:

import React from 'react';
class HelloWorld extends React.Component{
  constructor(props){
    super(props)
    this.state = {
      info:'用子組件的數(shù)據(jù)寫具名插槽 hello World'
    }
    this.elementSlot = "";
    if (this.props.element) {
      this.elementSlot = this.props.element(this.state.info);
    }
  }
  render(){
    return (
      <div>
        {this.elementSlot}
      </div>
    );
  }
}
export default HelloWorld;
復(fù)制代碼
import React from 'react';
import HelloWorld from './HelloWorld.js';
class Index extends React.Component{
  constructor(props) {
    super(props);
  }
  info(data){
    return(
      <span>{data}</span>
    )
  }
  render() {
    return (
      <HelloWorld element={this.info}>
      </HelloWorld>
    )
  }
}
export default Index;
復(fù)制代碼

函數(shù)組件的寫法

import { useState } from "react";

export default function HelloWorld(props) {
  const { children, element } = props;
  const [info] = useState('用子組件的數(shù)據(jù)寫具名插槽 hello World')
  let elementSlot = "";
  if (element) {
    elementSlot = element(info);
  }
  return (
    <div>
      {elementSlot}
      {children}
    </div>
  );
}
復(fù)制代碼
import HelloWorld from './HelloWorld.js';

export default function Index(){
  const info = (data) =>{
    return (
      <span>{data}</span>
    )
  }
  return (
    <HelloWorld element={info}></HelloWorld>
  )
}
復(fù)制代碼

小結(jié)

以上從Vue開發(fā)一個(gè)組件會(huì)用到的技術(shù)炕矮,在React中尋找對(duì)應(yīng)的實(shí)現(xiàn)方案的角度來入門React,讀完你應(yīng)該會(huì)用React開發(fā)一些簡單的頁面者冤,并能把頁面分割成一個(gè)個(gè)組件肤视,并在組件之間進(jìn)行數(shù)據(jù)交互。下一篇文章將介紹開發(fā)組件時(shí)在Vue中那些常用的指令在React中是如何實(shí)現(xiàn)的涉枫。

作者:紅塵煉心
鏈接:https://juejin.cn/post/6975864046058733576

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末邢滑,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子拜银,更是在濱河造成了極大的恐慌殊鞭,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,372評(píng)論 6 498
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件尼桶,死亡現(xiàn)場(chǎng)離奇詭異操灿,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)泵督,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,368評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門趾盐,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人小腊,你說我怎么就攤上這事救鲤。” “怎么了秩冈?”我有些...
    開封第一講書人閱讀 162,415評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵本缠,是天一觀的道長。 經(jīng)常有香客問我入问,道長丹锹,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,157評(píng)論 1 292
  • 正文 為了忘掉前任芬失,我火速辦了婚禮楣黍,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘棱烂。我一直安慰自己租漂,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,171評(píng)論 6 388
  • 文/花漫 我一把揭開白布颊糜。 她就那樣靜靜地躺著哩治,像睡著了一般。 火紅的嫁衣襯著肌膚如雪衬鱼。 梳的紋絲不亂的頭發(fā)上锚扎,一...
    開封第一講書人閱讀 51,125評(píng)論 1 297
  • 那天,我揣著相機(jī)與錄音馁启,去河邊找鬼驾孔。 笑死,一個(gè)胖子當(dāng)著我的面吹牛惯疙,可吹牛的內(nèi)容都是我干的翠勉。 我是一名探鬼主播,決...
    沈念sama閱讀 40,028評(píng)論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼霉颠,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼对碌!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起蒿偎,我...
    開封第一講書人閱讀 38,887評(píng)論 0 274
  • 序言:老撾萬榮一對(duì)情侶失蹤朽们,失蹤者是張志新(化名)和其女友劉穎怀读,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體骑脱,經(jīng)...
    沈念sama閱讀 45,310評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡菜枷,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,533評(píng)論 2 332
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了叁丧。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片啤誊。...
    茶點(diǎn)故事閱讀 39,690評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖拥娄,靈堂內(nèi)的尸體忽然破棺而出蚊锹,到底是詐尸還是另有隱情,我是刑警寧澤稚瘾,帶...
    沈念sama閱讀 35,411評(píng)論 5 343
  • 正文 年R本政府宣布牡昆,位于F島的核電站,受9級(jí)特大地震影響摊欠,放射性物質(zhì)發(fā)生泄漏迁杨。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,004評(píng)論 3 325
  • 文/蒙蒙 一凄硼、第九天 我趴在偏房一處隱蔽的房頂上張望铅协。 院中可真熱鬧,春花似錦摊沉、人聲如沸狐史。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽骏全。三九已至,卻和暖如春尼斧,著一層夾襖步出監(jiān)牢的瞬間姜贡,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,812評(píng)論 1 268
  • 我被黑心中介騙來泰國打工棺棵, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留楼咳,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,693評(píng)論 2 368
  • 正文 我出身青樓烛恤,卻偏偏與公主長得像母怜,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子缚柏,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,577評(píng)論 2 353

推薦閱讀更多精彩內(nèi)容