React组件复用

render props模式:

使用步骤:1.创建Mouse组件,在组件中提供要复用的状态逻辑代码。

                  2.将复用的状态作为props.render(state)方法的参数,暴漏到组件外部。

                  3.使用props.render()返回值作为需要渲染的内容。

可用children代替render

其他部分和props.render模式一样。

高阶组件

高阶组件是一个函数,接受要包装的组件,返回增强后的组件。

高阶组件的使用:

1.创建一个函数,名称约定以with开头。

2.指定函数参数,参数以大学字母开头。

3.在函数内部创建一个类组件,提供复用逻辑代码,并返回。

return <wrappedComponent {...this.state} [...this.props}></wrapppedComponent>

4.在该组件中,渲染参数组件,通史将状态通过props传递给参数组件。

5.调用该高阶组件,传入要增强的组件,通过返回值拿到增强后的组件,并通过其渲染到页面中。

import React from "react";

function withMouse(WrappedComponent) {

  class Mouse extends React.Component {

    state = {

      x: 0,

      y: 0,

    };

    handleMove = (e) => {

      this.setState({

        x: e.clientX,

        y: e.clientY,

      });

    };

    componentDidMount() {

      window.addEventListener("mousemove", this.handleMove);

    }

    componentWillUnmount() {

      window.removeEventListener("mousemove", this.handleMove);

    }

    render() {

      return <WrappedComponent {...this.state}></WrappedComponent>;

    }

  }

  return Mouse;

}

const Position = (props) => (

  <p>

    鼠标当前的位置:{props.x},{props.y}

  </p>

);

const MousePosition = withMouse(Position);

class Parent extends React.Component {

  render() {

    return (

      <div className="Parent">

        <MousePosition></MousePosition>

      </div>

    );

  }

}

export default Parent;

高阶组件设置displayName:

为什么要设置diaplayName:使用高阶组件,得到的高阶组件名称相同。

决解方法:设置displayName。displayName的作用:用于设置调试信息。

使用:Mouse.displayName = `WithMouse${getDisplayName(wrappedComponent)}`

          function getDisplayName(wrappedComponent){

                return WrappedComponent.displayName.displayName || WrappedComponent.name ||                 ‘component’ ;       

        }

高阶组件传递props:

问题:props丢失。原因:高阶组件没有往下传递props。

解决方法:渲染WrappedComponent时将state和this.props一起传递给组件。

<WrappedComponent {...this.state} {...this.props}></WrappedComponent>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值