新聞中心
前言
找工作時(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)如下所示:
- ├── package.json
- ├── .umirc.ts
- ├── .env
- ├── dist
- ├── mock
- ├── public
- └── src
- ├── .umi
- ├── layouts/index.tsx
- ├── pages
- ├── index.less
- └── index.tsx
- └── app.ts
打開(kāi) .umirc.ts 文件,其內(nèi)容如下所示
- import { defineConfig } from 'umi';
- export default defineConfig({
- nodeModulesTransform: {
- type: 'none',
- },
- routes: [
- { path: '/', component: '@/pages/index' },
- ],
- fastRefresh: {},
- });
其路由是在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ù)組件:
- export default function HelloWorld() {
- return (
hello world- );
- }
ES6的class形式,稱為類組件:
- import React from 'react';
- export default class HelloWorld extends React.Component {
- constructor(props) {
- super(props);
- }
- render() {
- return (
hello world- );
- }
- }
這里要注意函數(shù)名的首字母要大寫。在函數(shù)中的return后面用JSX語(yǔ)法來(lái)開(kāi)發(fā)組件的UI部分。
另外還要注意在return后面的內(nèi)容最外面要用()括起來(lái),否則在return同一行后面最少跟一個(gè)<才可以,如下所示:
- export default function HelloWorld() {
- return <
- div>hello world
這樣看起來(lái)是不是怪怪的,所以最好加個(gè)()。
2.2 綁定 Class 和 Style
關(guān)于組件的CSS部分,其最重要的是綁定 Class 和 Style,才能給組件的HTML添加樣式。
先來(lái)看一下 Class 與 Style 是固定不變,React 中是怎么綁定的。
- export default function HelloWorld() {
- return (
- className="title head"
- style={{color:'red',fontSize:'16px'}}
- >
- hello world
- );
- }
React中是用className來(lái)綁定 Class,用style來(lái)綁定 Style。其中style接受的值是一個(gè)對(duì)象,且用{}中括號(hào)傳入,而且對(duì)象的屬性名只能用駝峰式 (camelCase) 來(lái)命名。
在來(lái)看一下 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 (
- className={`${this.state.className} ${this.state.isHead ? 'head' : ''}`}
- style={this.state.styleData}
- >
- hello world
- );
- }
- }
- 函數(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 (
- className={`${className} ${isHead ? 'head' : ''}`}
- style={styleData}
- >
- hello world
- );
- }
在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先把組件引入并命名。
- import HelloWorld from './HelloWorld.js'
- export default function Index(){
- return (
- )
- }
在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ù):
- this.state = {
- styleData: { color: 'red', 'fontSize': "16px" },
- isHead: true,
- className: 'title'
- };
- 在函數(shù)組件的寫法中使用useState這個(gè)React Hook定義了數(shù)據(jù):
- const [styleData] = useState({ color: 'red', 'fontSize': "16px" });
- const [isHead] = useState(true);
- 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ù)。
- 類組件的寫法:
- import React from 'react';
- class HelloWorld extends React.Component {
- constructor(props) {
- super(props);
- }
- render() {
- return (
{this.props.title}- );
- }
- }
- HelloWorld.defaultProps = {
- title: 'hello world'
- };
- 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ù)組件的寫法:
- import { useState } from 'react';
- export default function HelloWorld(props) {
- const {title = 'hello world'} = props;
- return (
{title}- );
- }
函數(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ù)
- 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 (
- styleData={styleData}
- isHead={isHead}
- className={className}
- />
- )
- }
- 傳遞字符串類型的靜態(tài)數(shù)據(jù)
- 傳遞數(shù)字類型的靜態(tài)數(shù)據(jù)
- 傳遞布爾值類型的靜態(tài)數(shù)據(jù)
- 傳遞數(shù)組類型的靜態(tài)數(shù)據(jù)
- 傳遞對(duì)象類型的靜態(tài)數(shù)據(jù)
可見(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事件
- 類組件的寫法:
- import React from 'react';
- export default class HelloWorld extends React.Component {
- constructor(props) {
- super(props);
- // 為了在回調(diào)中使用 `this`,這個(gè)綁定是必不可少的
- thisthis.handleClick = this.handleClick.bind(this);
- }
- handleClick() {
- console.log('點(diǎn)擊事件');
- }
- render() {
- return (
hello world- );
- }
- }
- 函數(shù)組件的寫法:
- export default function HelloWorld() {
- const handleClick = ()=>{
- console.log('點(diǎn)擊事件');
- }
- return (
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)如下所示:
- 類組件的寫法:
- import React from 'react';
- export default class HelloWorld extends React.Component {
- constructor(props:any) {
- super(props);
- console.log(this.props)
- thisthis.handleClick = this.handleClick.bind(this);
- }
- handleClick() {
- this.props.onClick();
- }
- render() {
- return (
hello world- );
- }
- }
- import React from 'react';
- import HelloWorld from './HelloWorld';
- export default class Grandfather extends React.Component {
- handleClick() {
- console.log('點(diǎn)擊事件');
- }
- render() {
- return (
{ this.handleClick() }}> - )
- }
- }
- 函數(shù)組件的寫法:
- export default function HelloWorld(props) {
- const { onClick } = props
- const handleClick = () => {
- onClick();
- }
- return (
hello world- );
- }
- import HelloWorld from './HelloWorld';
- export default function Index(){
- const handleClick = ()=>{
- console.log('點(diǎn)擊事件');
- }
- return (
{ handleClick() }}> - )
- }
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è)綁定是必不可少的
- thisthis.handleClick = this.handleClick.bind(this);
- }
- handleClick() {
- this.setState(state => ({
- title: 'hello react',
- className: 'title active'
- }));
- }
- render() {
- return (
- className={className}
- onClick={this.handleClick}
- >{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ù)組件的寫法:
- 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 (
- className={className}
- onClick={handleClick}
- >
- {title}
- );
- }
在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” 。
- 類組件的寫法:
- import React from 'react';
- class HelloWorld extends React.Component {
- constructor(props) {
- super(props);
- thisthis.handleChangeTitle=this.handleChangeTitle.bind(this);
- }
- handleChangeTitle(){
- this.props.changeTitle('hello React');
- }
- render() {
- return (
- {this.props.title}
- );
- }
- }
- HelloWorld.defaultProps = {
- title: 'hello world'
- };
- export default HelloWorld;
- import HelloWorld from './HelloWorld.js'
- import React from 'react'
- class Index extends React.Component {
- constructor(props) {
- super(props);
- this.state={
- info:'hello world'
- };
- thisthis.handleChangeTitle=this.handleChangeTitle.bind(this);
- }
- handleChangeTitle(data){
- this.setState(state =>{
- return {
- info:data
- }
- })
- }
- render() {
- return (
- title={this.state.info}
- changeTitle={this.handleChangeTitle}>
- );
- }
- }
- export default Index;
- 函數(shù)組件的寫法:
- export default function HelloWorld(props: any) {
- const { title = 'hello world', changeTitle } = props;
- const handleChangeTitle = () => {
- changeTitle('hello React')
- }
- return (
- {title}
- );
- }
- 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 (
- )
- }
在父組件中定義一個(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。
- 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ù)改變了');
- }
- }
- 函數(shù)組件的寫法
在函數(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)保持不變。
- import {useEffect,useRef} from 'react';
- export function useWatch(value,callback){
- const oldValue = useRef();
- useEffect(() =>{
- callback(value,oldValue.current);
- oldValue.current=value;
- },[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ù)。
- 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])
- }
再添加immediate配置來(lái)控制在組件初次渲染后是否馬上執(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])
- }
另外Vue的watch還返回一個(gè)unwatch函數(shù),調(diào)用unwatch函數(shù)可以停止監(jiān)聽(tīng)該數(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;
- }
- 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 (
{title}- );
- }
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)方法也不同。
- 類子組件的寫法:
- 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 (
- {this.state.title}
- );
- }
- }
- import React from 'react';
- import HelloWorld from './HelloWorld.js';
- class Index extends React.Component {
- constructor(props) {
- super(props)
- this.myCom = React.createRef();
當(dāng)前文章:從 Vue2.0 到 React17 —— React 開(kāi)發(fā)入門
轉(zhuǎn)載源于:http://www.dlmjj.cn/article/ccchpph.html
其他資訊
- 在c中如何用html將數(shù)據(jù)顯示出來(lái)
- Linux自動(dòng)斷開(kāi)網(wǎng)絡(luò)連接:讓你省心又安全(linux自動(dòng)斷開(kāi)連接)
- 基于Redis實(shí)現(xiàn)跨系統(tǒng)數(shù)據(jù)遷移(redis跨系統(tǒng)數(shù)據(jù)遷移)
- 數(shù)據(jù)庫(kù)系統(tǒng)的時(shí)間錯(cuò)了,怎么辦? (數(shù)據(jù)庫(kù)系統(tǒng)當(dāng)前時(shí)間不正確)
- windows裝系統(tǒng)安裝文件位置?(開(kāi)機(jī)windows選擇系統(tǒng)文件夾)


咨詢
建站咨詢
