React组件的二三事

一、起步

创建一个React项目

1.创建项目:npx create-react-app my-app

2.打开项目:cd  my-app

3.启动项目:npm  start 

4.暴露配置项:npm  run  eject

二、组件

组件,从概念上类似于 JavaScript 函数。它接受任意的入参(即 “props”),并返回⽤于描述⻚面展示内容的 React 元素。

组件有两种形式:class组件和function组件。

class组件

class组件通常拥有状态生命周期继承于Component实现render⽅法

用class组件创建一个 Clock:

import React, { Component } from "react"

export default class ClassComponent extends Component {

    constructor(props) {

        super(props);

        // 存储状态,在构造函数中初始化状态

        this.state = {

            date: new Date()

        };

    }

    // 组件挂载完成后执行:启动定时器每秒更新状态

    componentDidMount() {

        this.timer = setInterval(() => {

            // 更新state,不能用this.state

            this.setState({

                date: new Date()

            })

        }, 1000);

    }

    // 组件卸载之前执行:停止定时器

    componentWillUnmount() {

        clearInterval(this.timer);

    }

    componentDidUpdate() { // 每次有值更新都会执行

        console.log("componentDidUpdate")

    }

    render() {

        const { date } = this.state;

        return (

            <div>

                <h3>ClassComponent</h3>

                <p>{date.toLocaleTimeString()}</p>

            </div>

        )

    }

}

function组件

函数组件通常无状态,仅关注内容展示,返回渲染结果即可。

从React16.8开始引入了hooks,函数组件也能够拥有状态

用function组件创建一个 Clock: 

import React, { useState, useEffect} from "react";

export function FunctionComponent(props) {

    const [date, setDate] = useState(new Date())

    useEffect(() => { // 副作用

        // 相当于componentDidMount、componentDidUpdate、componentWillUnmount的集合

        const timer = setInterval(() => {

            setDate(new Date())

        }, 1000)

        return () => clearInterval(timer) // 组件卸载的时候执行

    },[])

    return (

        <div>

            <h3>FunctionComponent</h3>

            <p>{date.toLocaleTimeString()}</p>

        </div>

    )

}

三、正确使用setState

setState(partialState, callback)

1. partialState:object|function

⽤于产生与当前state合并的子集。

2. callback:function

state更新之后被调⽤。 

关于 setState() 你应该了解三件事:

1.不要直接修改 State

例如,此代码不会重新渲染组件:

// 错误示范

this.state.comment = 'Hello';

而是应该使用 setState() :

// 正确使⽤

this.setState({

  comment: 'Hello'

});

2.State 的更新可能是异步的

出于性能考虑,React 可能会把多个 setState() 调⽤合并成⼀个调用。

观察以下例子中log的值和button显示的counter。

setState在合成事件和生命周期中是异步的:

import React, { Component } from "react"

export default class SetStatePage extends Component {

    constructor(props) {

        super(props);

        this.state = {

            counter: 0

        }

    }

    componentDidMount() {

        this.changeValue(1);

    }

    changeValue = (v) => {

        // setState在合成事件和生命周期中是异步的,这里说的异步其实是批量更新,达到优化性能的目的

        this.setState({

            counter: this.state.counter + v

        })

        console.log("counter", this.state.counter);

    }

    setCounter = () => {

        this.changeValue(1);

    }

    render() {

        const { counter } = this.state;

        return (

            <div>

                <h3>SetStatePage</h3>

                <button onClick={this.setCounter}>{counter}</button>

            </div>

        )

    }

}

使用定时器:setState在setTimeout中是同步的:

import React, { Component } from "react"

export default class SetStatePage extends Component {

    constructor(props) {

        super(props);

        this.state = {

            counter: 0

        }

    }

    changeValue = (v) => {

        this.setState({

            counter: this.state.counter + v

        })

        console.log("counter", this.state.counter);

    }

    setCounter = () => {

        // setState在setTimeout中是同步的

        setTimeout(() => {

            this.changeValue(1);

        }, 0);

    }

    render() {

        const { counter } = this.state;

        return (

            <div>

                <h3>SetStatePage</h3>

                <button onClick={this.setCounter}>{counter}</button>

            </div>

        )

    }

}

原生事件中修改状态:setState在原生事件中是同步的:

import React, { Component } from "react"

export default class SetStatePage extends Component {

    constructor(props) {

        super(props);

        this.state = {

            counter: 0

        }

    }

    componentDidMount() {

        document.getElementById('test').addEventListener('click', this.changeValue);

    }

    changeValue = () => {

        // setState在原生事件中是同步的

        this.setState({

            counter: this.state.counter + 1

        })

        console.log("counter", this.state.counter);

    }

    render() {

        const { counter } = this.state;

        return (

            <div>

                <h3>SetStatePage</h3>

                <button id="test">原生事件*{counter}</button>

            </div>

        )

    }

}

在回调中获取状态值:setState在回调中是同步的:

import React, { Component } from "react"

export default class SetStatePage extends Component {

    constructor(props) {

        super(props);

        this.state = {

            counter: 0

        }

    }

    changeValue = (v) => {

        this.setState({

            counter: this.state.counter + v

        },() => {

            // callback就是在state更新完成之后执行

            console.log("counter", this.state.counter);

        })

    }

    setCounter = () => {

        this.changeValue(1)

    }

    render() {

        const { counter } = this.state;

        return (

            <div>

                <h3>SetStatePage</h3>

                <button onClick={this.setCounter}>{counter}</button>

            </div>

        )

    }

}

总结: setState只有在合成事件和生命周期函数中是异步的,在原⽣事件和setTimeout中都是同步的,这⾥的异步其实是批量更新。

3.State 的更新会被合并

import React, { Component } from "react"

export default class SetStatePage extends Component {

    constructor(props) {

        super(props);

        this.state = {

            counter: 0

        }

    }

    changeValue = (v) => {

      this.setState({

            counter: this.state.counter + v

        },() => {

            console.log("counter", this.state.counter);

        })

    }

    setCounter = () => {

        this.changeValue(1); // 不会执行

        this.changeValue(2); // 不会执行

        this.changeValue(3); // 会执行

    }

    render() {

        const { counter } = this.state;

        return (

            <div>

                <h3>SetStatePage</h3>

                <button onClick={this.setCounter}>{counter}</button>

            </div>

        )

    }

}

如果想要链式更新state:

import React, { Component } from "react"

export default class SetStatePage extends Component {

    constructor(props) {

        super(props);

        this.state = {

            counter: 0

        }

    }

    changeValue = (v) => {

        // setState函数

        this.setState(state => {

            return {

                counter: state.counter + v

            }

        })

    }

    setCounter = () => {

        this.changeValue(1); // 会执行

        this.changeValue(2); // 会执行

        this.changeValue(3); // 会执行

    }

    render() {

        const { counter } = this.state;

        return (

            <div>

                <h3>SetStatePage</h3>

                <button onClick={this.setCounter}>{counter}</button>

            </div>

        )

    }

}

四、组件复合

复合组件给与你足够的敏捷去定义自定义组件的外观和行为,这种方式更明确和安全。如果组件间有公⽤用的⾮UI逻辑,将它们抽取为JS模块导入使⽤而不是继承它。

不具名:

HomePage.js文件内容如下:

import React, { Component } from "react";

import Layout from './Layout'

export default class HomePage extends Component {

    render() {

        return (

            <Layout showTopBar={false} showBottomBar={true} title="首页">

                <div>

                    <h3>HomePage</h3>

                </div>

            </Layout>

        )

    }

}

Layout.js文件内容如下:

import React, { Component } from "react";

import TopBar from '../components/TopBar'

import BottomBar from '../components/BottomBar'

export default class Layout extends Component {

    componentDidMount() {

        const { title = "商城" } = this.props;

        document.title = title;

    }

    render() {

        const { children, showTopBar, showBottomBar } = this.props;

        console.log('children', children)

        return (

            <div>

                {showTopBar && <TopBar />}

                {children}

                <h3>Layout</h3>

                {showBottomBar && <BottomBar />}

            </div>

        )

    }

}

TopBar.js文件内容如下:

import React, { Component } from "react";

export default class TopBar extends Component {

    render() {

        return (

            <div>

                <h3>TopBar</h3>

            </div>

        )

    }

}

BottomBar.js文件内容如下:

import React, { Component } from "react";

export default class BottomBar extends Component {

    render() {

        return (

            <div>

                <h3>BottomBar</h3>

            </div>

        )

    }

}

具名:传个对象进去

userPage.js文件内容如下:

import React, { Component } from "react";

import Layout from './Layout'

export default class UserPage extends Component {

    render() {

        return (

            <Layout showTopBar={true} showBottomBar={true} title="用户中心">

                {

                    {

                        content: (

                            <div>

                                <h3>UserPage</h3>

                            </div>

                        ),

                        text: "这是一个文本",

                        btnClick: () => {

                            console.log("btnClick")

                        }

                    }

                }

            </Layout>

        )

    }

}

Layout.js文件内容如下:

import React, { Component } from "react";

import TopBar from '../components/TopBar'

import BottomBar from '../components/BottomBar'

export default class Layout extends Component {

    componentDidMount() {

        const { title = "商城" } = this.props;

        document.title = title;

    }

    render() {

        const { children, showTopBar, showBottomBar } = this.props;

        console.log('children', children)

        return (

            <div>

                {showTopBar && <TopBar />}

                {children.content}

                {children.text}

                <button onClick={children.btnClick}>button</button>

                <h3>Layout</h3>

                {showBottomBar && <BottomBar />}

            </div>

        )

    }

}

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,333评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,812评论 1 298
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 110,016评论 0 246
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,293评论 0 214
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,650评论 3 288
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,788评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,003评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,741评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,462评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,681评论 2 249
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,168评论 1 262
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,528评论 3 258
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,169评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,119评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,902评论 0 198
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,846评论 2 283
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,719评论 2 274

推荐阅读更多精彩内容