react-进阶知识

一、组件通信

  1. 父组件传递数据给儿组件 props接收传递给组件的数据
  • 传递数据: 给组件标签添加属性
  • 接收数据: 函数组件通过参数props接收数据,类组件通过this.props接收数据
<Hell0 name="jack" age={19}/>

//函数组件
function Hello(props) {
 console.log(props)
 return (
     <div>接收到数据:{props.name}</div>
 )
}

//类组件
class Hello extends React.component {
    render() {
        return (
            <div>接收到的数据: {this.props.age}</div>
        )
    }
}

  • props只能接收不能修改
  • 注意: 使用类组件时,如果写了构造函数,应该将props传递给super(),否则,无法在构造函数中获取props
  • 可以传递任何数据
  1. 子组件传递数据给父组件 回调函数
  • 父组件提供一个回调函数(用于接收数据)
  • 将该函数作为属性的值,传递给子组件
    class Parent extends React.Component {
        getChildMsg = (msg) => {
            console.log('接收到子组件数据',msg)
        }
        render() {
            return (
                <div>
                    子组件: <Child getMsg={this.getChildMsg}/>
                </div>
            )
        }
    }

    class Child extends React.Component {
        state = {
            childMsg: 'React'
        }
        handleClick = () => {
            this.props.getMsg(this.state.childMsg)
        }
        render() {
            return (
                <div className="child">
                    子组件: <button onClick={this.handleClick}>点我</button>
                </div>
            )
        }
    }
  1. 兄弟组件
  • 将共享状态提升到最近的父组件,由公共父组件管理这个状态
    class Parent extends React.Component {
        state = {
            count: 0
        }
        handleClick = () => {
            this.setState({
                count: this.state.count + 1
            })
        }
        render() {
            return (
                <div>
                    子组件1<Child1 getMsg={this.state.count}/>
                    子组件2<Child2 getMsg={this.handleClick}/>
                </div>
            )
        }
    }

    class Child1 extends React.Component {
        render() {
            return <h1>计数器: {this.props.count}</h1>
        }
    }
props.count
    class Child2 extends React.Component {
        handleClick = () => {
            this.props.getMsg()
        }
        render() {
            return (
                <div className="child">
                    子组件: <button onClick={this.handleClick}>+1</button>
                </div>
            )
        }
    }
  1. countext
  • 作用: 跨组件传递数据
//1. 调用React.createContext()创建Provider(提供数据)和Consumer (消费数据)两个组件。
const {Provider,Consumer} = React.createContext()
//2. 使用Provider组件作为父节点
//3. 设置value属性,表示要传递的数据
<Provider value="pink">
    <div className="App">
        <Child1 />
    </div>
</Provider>
//4. 调用Consumer组件接收数据
<Consumer>
    {data => <span>{data}</span>}
</Consumer>
//创建组件
const {Provider,Consumer} = React.createContext()
class App extends React.Component {
    render() {
        return (
            <Provider value="pink">
                <div className="app">
                    <Node />
                </div>
            </Provider>
        )
    }
}

class Node = props {
    render() {
        return (
            <div className="node">
                <SubNode />
            </div>
        )
    }
}

class SubNode = props {
    render() {
        return (
            <div className="subnode">
                <Consumer>
                    {data => <span>{data}<span>}
                </Consumer>
            </div>
        )
    }
}
  1. props深入
  1. children
  • children属性:表示组件标签的子节点。当组件标签有子节点时,props就会有该属性
  • children为jsx、组件、函数
const App = props => {
    console.log(props)
    return (
        <div>
            <h1>组件标签的子节点:</h1>
            <span>{props.children}</span>
        </div>
    )
}

<App>我是子节点</App>
  1. prop校验
//安装prop-types npm i prop-types
//导入prop-types包
import PropTypes from 'prop-types'
//使用组件名propTypes={}来给组件的props添加校验规则
App.propTypes = {
    colors: PropTypes.array
}
//约束规则 
//类型: array、bool、func、number、object、string
//React元素类型: element
//必填项:isRequired
//特定结构的对象: shape({})
optionalFunc: PropTypes.func
requiredFunc: PropTypes.func.isRequired
optionalObjectWithShape: PropTypes.shape({
    color: PropTypes.string
    fontsize: PropTypes.number
})

//默认值
App.defaultProps = {
    pageSize: 10
}

二、组件生命周期

  1. 生命周期的三个阶段:创建时、更新时、卸载时
    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rO3rqTse-1634779131349)(/images/16775500-102dbe772034e8fa.webp)]

1)创建时:constructor() -> render() -> componentDidMount()

钩子函数触发时机作用
constructor创建组件时,最先执行初始化state、为事件处理程序绑定this
render每次组件渲染都会触发渲染ui,不能调用setState()
componentDidMount组件挂载(完成Dom渲染后)发送网络请求、Dom操作

2)更新时:render() -> componentDidUpdate()

  • New Props 新的传值、setState()修改值 、forceUpdate()强制刷新时
    | 钩子函数 | 触发时机 | 作用 |
    | ---- | ---- | — |
    | render | 每次组件渲染都会触发 | 渲染ui,不能调用setState() |
    | componentDidUpdate | 组件挂载(完成Dom渲染后) | 发送网络请求、Dom操作 |

  • 注意: 如果要setState()必须放在一个if条件中

  • 否则会出现递归更新、无限调用

  • if判断是否更新啦值

  1. 卸载时: componentWillUnmount
钩子函数触发时机作用
componentDidUpdate组件卸载(从页面中消失)执行清理工作(比如:清理定时器)

三、render-props和高阶组件

  1. react组件复用 复用:state和 操作state的方法
  2. 两种方式: render props模式 和 高阶组件(HOC)
  • render props模式
  • 思路:将要复用的state和操作state的方法封装到一个组件中
  • 在使用组件时,添加一个值为函数的prop,通过函数参数来获取(需要组件内部实现)
  • 使用该函数的返回值作为要渲染的ui内容(需要组件内部实现)
    <Mounse render={(mouse) => (
        <p>{mouse.x}{mouse.y}</p>
    )}/>

    //创建组件
    class Mouse extends React.Component {
        //鼠标位置state
        state = {
            x: 0,
            y: 0
        }
        //鼠标移动事件的事件处理程序
        handleMouseMove = e => {
            this.setState({
                x: e.clientX,
                y: e.clientY
            })
        }
        //把this.state暴露到外部
        // children代替render属性
        // 注意: 并不是该模式叫render props就必须使用名render的prop,实际上可以使用任意名称的prop
        render() {
            //return this.props.render(this.state)
            return this.props.children(this.state)
        }
        //监听鼠标移动事件
        componentDidMount() {
            window.addEventListener('mousemove',this.handleMouseMove)
        }
        //卸载时去掉事件
        componentWillUnmount() {
            window.removeEventListener('mousemove',this.handleMouseMove)
        }
    }
    //render props模式添加props校验
    Mouse.propTypes = {
        children: PropTypes.func.isRequired
    }
    // 将要复用的状态作为props.render(state)方法的参数,暴露到组件外部
    class App extends React.Component {
        render() {
            return (
                <div>
                    <h1>render prop</h1>
                    <Mouse render={(mouse) => (
                        <p>{mouse.x}{mouse.y}</p>
                    )}/>
                </div>
            )
        }
    }
  • 高阶组件
  • 思路: 高阶组件是一个函数,接收要包装的组件,返回增强后的组件
  • 告诫组件内部创建一个类组件,在这个类组件中提供复用的状态逻辑代码,通过prop将复用的状态传递为被包装组件WrappedComponent
const EnhanceComponet = withHOC(WrappedComponet)

class Mouse extends React.component {
    render() {
        return <WrappedComponent {...this.state}/>
    }
}
  • 使用步骤
  • 1.创建一个函数,名称约定以with开头
  • 2.指定函数参数,参数应该以大写字母开头(作为要渲染的组件)
  • 3.在函数内部创建一个类组件,提供复用的状态逻辑代码,并返回
  • 4.在该组件中,渲染参数组件,同时将状态通过prop传递给参数
  • 5.调用该高阶组件,传入要增强的组件,通过返回值拿到增强后的组件,将其渲染到页面中
//创建高阶组件
function withMouse(WrappedComponent){
    // 该组件提供复用的状态逻辑
    class Mouse extends React.Component {
        //鼠标状态
        state = {
            x: 0,
            y: 0
        }
        //修改值
        handleMouseMove = e=> {
            this.setState({
                x: e.clientX,
                y: e.clientY
            })
        }
        //控制鼠标状态的逻辑
        componentDidMount() {
            window.addEventListener('mousemove',this.handleMouseMove)
        }
        //卸载时去掉事件
        componentWillUnmount() {
            window.removeEventListener('mousemove',this.handleMouseMove)
        }
        render() {
            //this.props丢失设置
            return <WrappedComponent {...this.state}{...this.props}></WrappedComponent>
        }
    }
    //调用displayname方法
    Mouse.dispalyName = `WithMouse${getDisplayName(WrappedComponent)}`
    return Mouse
}

//使用
const Position = props => {
    <p>
        鼠标当前位置: {props.x},{props.y}
    </p>
}
//获取增强后的组件
const MousePosition = withMouse(Position)

//设置获取name方法
function getDisplayName(WrappedComponent){
    return WrappedCompoent.displayName || WrappedComponent.name || 'Component'
}

class App extends React.Component {
    render() {
        return (
            <div>
                <h1>高阶组件</h1>
                {/*渲染增强后的组件*/}
                <MousePosition  a='1'/>
            </div>
        )
    }
}
高阶组件
  1. 函数当参数、或者当返回值
  2. 在原有组件上加上一些属性返回,包装一层
  3. 属性代理、反向代理
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值