美文网首页
React 基础

React 基础

作者: iCherries | 来源:发表于2020-02-23 16:33 被阅读0次

    1.渲染

    // index.jsx
    import React from 'react'
    import ReactDOM from 'react-dom'
    
    // React类负责逻辑控制, 比如修改数据 -> vdom
    // ReactDOM 类负责渲染, vdom -> dom
    // babel-loader     jsx -> vdom     <h1>React基础</h1>  => React.createElement('h1', 'React 基础')
    const jsx = <h1>React基础</h1>
    ReactDOM.render(jsx, document.getElementById('root'))
    

    2.组件

    一.组件有两种形式: class 组件和 function 组件

    class组件拥有状态和生命周期,继承与 Component, 实现 render 方法.

    // components/JsxText.jsx
    import React, { Component } from 'react'
    
    export default class JsxText extends Component {
        render() {
            return (
                <div>react 基础</div>
            )
        }
    }
    

    函数式组件

    // App.jsx
    import React from 'react'
    import JsxText from './components/JsxText'
    
    export default function App() {
        return (
            <div>
                <JsxText />
            </div>
        )
    }
    
    

    二.组件状态管理

    // components/State.jsx
    import React, { Component, useState, useEffect } from 'react'
    
    // class 组件
    class Time extends Component {
        state = {
            date: new Date()
        }
    
        componentDidMount() {
            // 定时器
            this.timer = setInterval(() => {
                this.setState({
                    date: new Date()
                })
            }, 1000)
        }
    
        componentWillMount() {
            clearInterval(this.timer)
        }
    
        render() {
            return (
                <div>
                    {this.state.date.toLocaleTimeString()}
                </div>
            );
        }
    }
    
    // 函数组件 useState, useEffect 
    // hooks 版本要求 >= 16.8.x
    function TimeFn() {
        // 创建状态, useState返回状态和修改状态的函数所组成的数组
        const [date, setDate] = useState(new Date())
    
        useEffect(() => {
            const timer = setInterval(() => {
                setDate(new Date())
            }, 1000)
            return () => { // 相当于 componentWillUnmount 狗子
                clearInterval(timer)
            }
        }, []) // 参数 2 指的依赖的状态, [] 中的值变化 useEffect 中的方法执行, 本案例只需执行一次,所以为空数组
    
        return (
            <div>
                {date.toLocaleTimeString()}
            </div>
        )
    }
    
    
    export default function State() {
        return (
            <div>
                <Time></Time>
                <TimeFn></TimeFn>
            </div>
        )
    }
    
    //App.jsx
    <div>
        {/* 状态管理 */}
        <State />
    </div>
    

    三.组件通信

    // State.jsx
    class Time extends Component {
        state = {
            date: new Date()
        }
    
        componentDidMount() {
            // 定时器
            this.timer = setInterval(() => {
                this.setState({
                    date: new Date()
                }, () => {
                    this.props.change(this.state.date)
                })
            }, 1000)
        }
    
        componentWillUnmount() {
            clearInterval(this.timer)
        }
        render() {
            return (
                <div>
                    {this.state.date.toLocaleTimeString()}
                    {this.props.name}
                </div>
            );
        }
    }
    
    function TimeFn(props) {
        // ......
        return (
            <div>
                {date.toLocaleTimeString()}
                {props.name}
            </div>
        )
    }
    
    export default function State() {
        return (
            <div>
                <Time name="cherries" change={(date) => { console.log(date.toLocaleTimeString()) }}></Time>
                <TimeFn name="cherries"></TimeFn>
            </div>
        )
    }
    
    使用 Context
    // components/ContentText.jsx
    import React, { useState } from 'react'
    
    // 1.创建上下文
    const Context = React.createContext()
    // 2.获取Provider 和 Consumer
    const { Provider, Consumer } = Context
    
    function Child(props) {
        return (
            <div onClick={props.add}>{props.counter}</div>
        )
    }
    
    export default function ContextText() {
        const [counter, setCounter] = useState(0)
    
        const add = () => {
            setCounter(counter + 1)
        }
    
        return (
            <Provider value={{counter, add}}>
                <Consumer>
                    { value => <Child {...value}></Child>}
                </Consumer>
                <Consumer>
                    { value => <Child {...value}></Child>}
                </Consumer>
            </Provider>
        )
    }
    
    // App.jsx
    export default function App() {
        return (
            <div>
                <ContextText/>
            </div>
        )
    }
    

    四.高阶组件

    // comopnents/Hoc.jsx
    import React from 'react'
    
    const Lesson = (props) => {
        return (
            <div>
                {props.stage} - {props.title}
            </div>
        )
    }
    
    const lessons = [
        { stage: 'React', title: 'React1' },
        { stage: 'React', title: 'React2' },
        { stage: 'React', title: 'React3' },
    ]
    
    // 定义高阶函数
    const withContent = Comp => props => {
        const content = lessons[props.index]
        return <Comp {...content} />
    }
    
    const LessonWithContent = withContent(Lesson)
    
    export default function Hoc() {
        return (
            <div>
                { [1,1,1].map((item, index) => (
                    <LessonWithContent key={index} index={index}></LessonWithContent>
                )) }
            </div>
        )
    }
    
    
    // App.jsx
    export default function App() {
        return (
            <div>
                <Hoc/>
            </div>
        )
    }
    
    提示: 支持装饰器配置: npm install -D @babel/plugin-proposal-decorators customize-cra
    const { addDecoratorsLegacy } = require("customize-cra");
    module.exports = override( ...,
        addDecoratorsLegacy()
    );
    

    五.组件复合(插槽)

    // components/Composition
    import React from 'react'
    
    function Dialog(props) {
        return <div style={{ border: '1px solid blue' }}>{props.children.def}</div>
    }
    
    export default function Composition() {
        return (
            <Dialog>
                // 普通插槽
                // {
                //     <h1>cherries</h1>
                // }
                // 具名插槽
                // {{
                //     def: (
                //         <h1>组件复合</h1>
                //     )
                // }}
            </Dialog>
        )
    }
    
    // components/Composition
    // 作用域插槽
    function Dialog(props) {
        const { def, content } = props.children({name: 'cherries', content: '内容'})
    
        return <div style={{ border: '1px solid blue' }}>
            {def}
            {content}
        </div>
    }
    
    export default function Composition() {
        return (
            <Dialog>
                {({name, content}) => ({
                    def: <h1>{name}</h1>,
                    content: <h2>{content}</h2>
                })}
            </Dialog>
        )
    }
    
    // App.jsx
    export default function App() {
        return (
            <div>
                <Composition/>
            </div>
        )
    }
    

    相关文章

      网友评论

          本文标题:React 基础

          本文链接:https://www.haomeiwen.com/subject/wdgjqhtx.html