chapter2.三、react高階組件,裝飾器

React 技術

高階組件

let Root = props => <div>{props.schoolName}</div>;react

若是要在上例的Root組件進行加強怎麼辦?例如將Root組件的div外部再加入其它div。app

let Wrapper = function (Component, props) {
    return (
        <div>
            {props.name}
            <hr />
            <Component />
        </div>
    );
};
let Root = props => <div>{props.name}</div>;

柯里化dom

import React from "react";
import ReactDom from "react-dom"

let Wrapper = function (Component) {
    function _wrapper (props) {
        return (
        <div>
            {props.name}
            <hr />
            <Component />
        </div>
    );
    }
    return _wrapper
};
let Root = props => <div>{props.schoolName}</div>;
let NewComp = Wrapper(Root) // 返回一個包裝後的元素
ReactDom.render(<NewComp name="Riper" />, document.getElementById('root'));

簡化Wrapper函數

import React from "react";
import ReactDom from "react-dom"

let Wrapper = function (Component) {
    return  (props) => 
        <div>
            {props.name}
            <hr />
            <Component />
        </div>
    ;
};
let Root = props => <div>{props.schoolName}</div>;
let NewComp = Wrapper(Root) // 返回一個包裝後的元素
ReactDom.render(<NewComp name="Riper" />, document.getElementById('root'));

繼續化簡this

import React from "react";
import ReactDom from "react-dom"

let Wrapper =  (Component) => (props) => 
        <div>
            {props.name}
            <hr />
            <Component />
        </div>

let Root = props => <div>{props.schoolName}</div>;
let NewComp = Wrapper(Root) // 返回一個包裝後的元素
ReactDom.render(<NewComp name="Riper" />, document.getElementById('root'));

裝飾器

新版ES2016中增長了裝飾器的支持,所以能夠使用裝飾器改造上面的代碼spa

裝飾器在ES2016能夠裝飾類,因此,將Root改寫成類code

import React from 'react';
import ReactDom from 'react-dom';

let Wrapper = Component => props =>
    (<div>
        {props.Name}
        <hr />
        <Component />
    </div>);

@Wrapper
class Root extends React.Component {
    render() {
        return <div>Root</div>;
    }
}

ReactDom.render(<Root Name="Riper" />, document.getElementById('root'));

能夠讓Root也顯示出name屬性blog

import React from 'react';
import ReactDom from 'react-dom';

let Wrapper = Component => props =>
    (<div>
        {props.Name}
        <hr />
        <Component {...props} />
    </div>);

@Wrapper
class Root extends React.Component {
    render() {
        return <div>{this.props.Name}</div>;
    }
}

ReactDom.render(<Root Name="Riper" />, document.getElementById('root'));

 

使用 <Component {...props} /> 至關於給組件增長了屬性。ip

帶參裝飾器

import React from 'react';
import ReactDom from 'react-dom';

let Wrapper = id => Component => props =>
    (<div id={id}>
        {props.Name}
        <hr />
        <Component {...props} />
    </div>);

@Wrapper("wrapper")
class Root extends React.Component {
    render() {
        return <div>{this.props.Name}</div>;
    }
}

ReactDom.render(<Root Name="Riper" />, document.getElementById('root'));

簡單改寫,就能夠獲得帶參裝飾器get

若是以爲很差接受,能夠先寫成原始的形式,熟悉了箭頭函數語法後,再改爲精簡的形式。

相關文章
相關標籤/搜索