1. 程式人生 > >react使用總結一:react 高階元件使用

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);