react使用总结一:react 高阶组件使用

1.IntervalEnhance.js定义高阶组件

// 高阶组件
// 主要用于替代旧的mixins



import React from 'react';
//1.还记得箭头函数吗?没错,这就是一个箭头函数。这个函数接受一个组件为输入参数,返回一个类。
//ComposedComponent就是输入参数,也就是需要包装增强的组件。
//export var IntervalEnhance就是把前面定义的函数命名为IntervalEnhance export出去给其他的模块使用。
export var IntervalEnhance = ComposeComponent => class extends ComposeComponent {
    // 2.displayName设定为ComponentEnhancedWithIntervalHOC是为了在DevTools中方便调试。
    // 在DevTools里这个组件就会被叫做ComponentEnhancedWithIntervalHOC
    static displayName = 'ComponentEnhancedWithIntervalHOC';

    //3.组件里的定义常量
    constructor(props) {
        super(props);
        this.state = {
            seconds: 0
        };
    }

    // 3.组件里的定义生命周期
    componentWillUnmount() {
        clearInterval(this.interval);
    }

    // 3.组件里的定义生命周期
    componentDidMount() {
        this.interval = setInterval(this.tick.bind(this), 1000);
    }

	// 3.组件里的定义方法
    tick() {
        this.setState({
            seconds: this.state.seconds + 1000
        });
    }

    // 3.组件里的定义方法
    alertFn(){
    	alert(1)
    }

    // 4.这样的写法会把当前高阶组件的全部props和state都发送给传入组件使用。
    render() {
    		const props = {
		      ...this.props,
		      alertFn: this.alertFn,
		      a:0
		    }

        return (
            // 4
            <ComposeComponent {...props} {...this.state}/>
        );
    }
}

2.Page1组件中使用高阶组件包裹组件,主要用途替代Mixins

import React, { Component } from 'react';
import {Router,Route,browserHistory} from 'react-router-dom';
import { Button } from 'antd-mobile';
import PropTypes from 'prop-types';

import { connect } from '../../react-redux.js';

// 1.引入高阶组件
import {IntervalEnhance} from '../../IntervalEnhance';


class Page1 extends Component {
	static propTypes = {
	    store: PropTypes.object
	}

	componentWillMount(){
		 // this.alertFn();
		// this.state.alertFn()
		// 
		console.log(this.props)
		// 3.使用高阶组件
		this.props.alertFn()
	}


	render() {
	    return (
	      <div className="page1">
	        这是page1
	        <br/>
	        themeColor:{ this.props.themeColor }
	        <br/>
	        {/*3.使用高阶组件*/}
	        <Button type="primary">{this.props.a}</Button>
	        <br/>
	       	{/*3.使用高阶组件*/}
	        <input onBlur={this.props.alertFn}/>	
	      </div>
	    );
  	}

}

const mapStateToProps = (state) => {
	  return {
	    themeColor: state.themeColor
	  }
}
Page1 = connect(mapStateToProps)(Page1)

// 2.高阶组件包裹
export default IntervalEnhance(Page1);

参考:https://blog.csdn.net/bbsyi/article/details/82381364

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值