React-native Pull-load, drop-down refresh component encapsulation

Source: Internet
Author: User
Tags arrays
react-native Custom Package Refresh component A few months did not write a blog, recently has been writing react and react-native, a few days ago just sent a version based on React-native mixed development app, these days quickly summed up. write Java classmate, then to learn react and react-native will be more easy to start, and there will be a sense of déjà vu, good, today I want to summarize the Refresh function and Android native implementation very similar, in Android native, Can be said to be a household name, the implementation in the react-native is the same simple, in the upgrade of Rn, Flatlist is an upgrade of the ListView, as if Recyclerview is an upgraded version of the ListView. OK, the nonsense is not much to say. Catalogue 1.FlatList Common attribute methods 2. Encapsulates a pull-up load, drop-down refresh component 1.FlatList Common attribute methods Data:? Array for simplicity, the data property currently supports only normal arrays. RenderItem: (info: {item:itemt, index:number}) =? React.element the components of each row are rendered according to the data of the row Onrefresh?:? () = Void if this option is set, a standard Refreshcontrol control is added to the head of the list to implement the "pull-down refresh" feature. At the same time you need to set the refreshing property correctly. Refreshing?: Boolean to set this property to True when waiting for new data to load, the list displays a symbol that is being loaded. Onendreachedthreshold: Number determines how far away from the bottom of the content the onendreached callback is triggered. Note This parameter is a ratio rather than a pixel unit. For example, 0.5 indicates that the distance from the bottom of the content is half of the visible length of the current list. Onendreached?:? (Info: {distancefromend:number}) = void when the list is scrolled to a distance that is less than onendreachedthreshold from the bottom of the content. Itemseparatorcomponent?:? Reactclass the dividing line component between rows and lines. Does not appear before the first line and after the last line.? Keyextractor: (item:itemt, index:number) = = String This function is used to generate a non-duplicate key for the given item. The function of key is to enable react to distinguish different individuals of similar elements so that they can determine where they change when refreshed, and reduce the overhead of re-rendering. If you do not specify this function, the default is to extract Item.key as the key value. If the Item.key does not exist, an array subscript is used. Listheadercomponent?:? Reactclass head assembly listfootercomponent?:? Reactclass tail component Listemptycomponent?:? Reactclass | Renders this component when the React.element list is empty. It can be a react Component, or it can be a render function, or a well-rendered element.

Extradata?: Any if there is data other than the use in the list (whether used in RenderItem or header or footer), specify in this attribute. At the same time, this data will need to modify its reference address (such as first copied to a new object or array), and then modify its value, otherwise the interface will probably not be refreshed. Note: Of course there are other property methods, please consult the documentation yourself Flatlist 2. Encapsulate a pull-up load, drop-down refresh component first define some proptypes to facilitate the extension of the component using the

static proptypes = {renderItem:PropTypes.func.isRequired,/* Method for rendering rows */ItemS
        EparatorComponent:PropTypes.func,/* methods for rendering line intervals */keyExtractor:PropTypes.func,/* Returns the method for each line of key */ ListFooterComponent:PropTypes.func,/* The method at the bottom of the render list */ListHeaderComponent:PropTypes.func,/* Render list header            Method */listUrl:PropTypes.string.isRequired,/* Get the URL of the list */fetchMethod:PropTypes.string, /* Get List Request method (default = Get) */fetchParams:PropTypes.object,/* Get list Request parameter */PAGESIZE:PROPTYPES.NUMB ER,/* Number of rows per page (default 20) */FormatData:PropTypes.func,/* methods to return array of arrays */_ref:propty
        Pes.func,/* Get the component instance properties */Auto:PropTypes.bool,/* Whether to query automatically when loading (default auto) */
    ShowFooterBoo:PropTypes.bool,/* Whether to show feet */ref:PropTypes.func,/* Get Component Instances */ };

2. Initialize the current status state

Constructor (props) {
        super (props);

        This._fetchurl = Props.listurl;
        This._fetchparams = Props.fetchparams;

        This.state = {
            list: [],/            * List data */
            pagenum:1,/          * Current page */
            count:0,/            * Total number of bars */
            REFRESHING:FA LSE,   /* is loading *
            /Isend:false,        /* Whether loading/
            isnotlist:false,/*    not querying the data */
            IsError: False,/      * Whether the query failed */
        }
    }

3.FlatList Component Properties encapsulate pre-render preparation

const {list, refreshing} = this.state;

        const {
            RenderItem,
            itemseparatorcomponent,
            keyextractor = (... arg) = = Arg[1],
            Listheadercomponent,
            extradata = {},
            Showfooterboo,
        } = this.props;
Flatlist Package
<flatlist
                data={list}
                Renderitem={renderitem}
                Onrefresh={this.onrefresh}
                refreshing={ refreshing}
                onendreachedthreshold={0.2}
                onendreached={this.onendreached}
                itemseparatorcomponent={ Itemseparatorcomponent}
                Keyextractor={keyextractor}
                Listheadercomponent={this.renderlistheader}
                Listfootercomponent={showfooterboo? This.renderListFooter:null}
                Listemptycomponent={this.renderlistempty}
                Ref={ref = This._listref = ref}
                Extradata={extradata}
            />

4.data={list} The list data is derived from the properties at the referencing component

5.renderitem={renderitem} in RenderItem derived from the item layout property of the referencing component

6.onrefresh={this.onrefresh} The drop-down refresh layout is as follows:

/** * Dropdown refresh * @return {void} */Onrefresh = () = {This.setstate ({
        Isend:false,}, () = {this.getlist ();
    }); }
/** * Get list * @return {void} */getList = (Isrefresh = true) + = {const {$fetch, Fetchmethod = ' get ', PageSize = $, Formatdata = ({data}) = ({Li St:data.records, Count:data.total,}), Fetchcatch = () = {},} = Thi

        S.props;

        const {list, pagenum, refreshing, isend} = this.state;

        if ((refreshing | | isend) &&!isrefresh) return; Const FETCHPAGENUM = Isrefresh?
        1:pagenum;

        Let Fetchpromise; if (fetchmethod.tolowercase () = = = ' Get ') {fetchpromise = $fetch. Get (This._fetchurl, {SIZE:PA
        Gesize, Current:fetchpagenum, ... this._fetchparams,});
                } else if (fetchmethod.tolowercase () = = = ' Post ') {fetchpromise = $fetch. Post (' ${this._fetchurl} ', {
       ... this._fetchparams,}); } else {throw new Error (' method type error! only ' get ' or ' post ');
        } this.setstate ({refreshing:true});
            Fetchpromise.then (data = {console.log (data);
                if (!data.success) {this.setstate ({iserror:true});
            Return
            } Const LISTDATA = formatdata (data); Const Currentlist = Isrefresh?
            ListData.list:list.concat (listdata.list);
                    /* Determine if the data is queried */if (fetchpagenum = = = 1 && listData.list.length = = 0) {this.setstate ({
            Isnotlist:true});
            } else {this.setstate ({isnotlist:false});
                    }/* If there is data added to the list */if (listData.list.length) {this.setstate ({
            List:currentlist, Pagenum:fetchpagenum + 1,});
  }          if (currentlist.length >= listdata.count) {this.setstate ({isend:true
            });
        } this.setstate ({count:listData.count,});
            }). catch (Err = {Console.log (err.response);
            if (!data.success) {this.setstate ({iserror:true});
        } fetchcatch (ERR);
        }). Finally (() = {this.setstate ({refreshing:false});
    }); }
Note: Get and post can be optimized according to your specific needs, where the network requests the fetch that is used.

The refreshing Boolean value in 7.refreshing={refreshing} is used to determine whether the current is in a refreshed state and is set to true when the requested data is refreshed.

8.onendreachedthreshold={0.2} When the sliding scale is 0.2, the onendreached method is triggered; onendreached={this.onendreached} pull-up loading is implemented as follows:

/**
     * Pull Load
     * @return {void} *
     /
    onendreached = () = {
        this.getlist (false);
    }
Note: This.getlist (False); method with drop-down refresh, parameter false for pull-up loading.

9.itemseparatorcomponent={itemseparatorcomponent} to customize a split line as follows:

Export Const Itemseparator = props = {
    Const {
        paddingleft = px (+),
        backgroundcolor = ' #fff ',
        bord Ercolor = ' #eee ',
    } = props;
    Return (
        <view style={{paddingleft, backgroundcolor}}>
            <view style={{height:1, BackgroundColor: bordercolor}}></view>
        </View>
    );
};

10.keyextractor={keyextractor} Use the ID of the current data, as follows:

Keyextractor={item = item.id}

11.listheadercomponent={this.renderlistheader} The head of the rendering, the code is as follows:

/**
     * Render list header
     *
    /Renderlistheader = () = {
        Const {count} = this.state;
        const {listheadercomponent = () = <View></View>} = this.props;
        Return listheadercomponent (this.state);
    }
Note: Layouts are defined according to their needs.

12.listfootercomponent={showfooterboo? This.renderListFooter:null} Property Showfooterboo Boolean value to control whether the foot is displayed, the layout of the foot is defined as follows:

    /**
     * Render list Bottom
     * @return {reactcomponent}
     *
    /renderlistfooter = () = {
        Const { Listfootercomponent = This.defaultlistfooter} = this.props;
        const {isend, refreshing} = this.state;
        Return This.defaultlistfooter (isend, refreshing);
    }
/**
     * List Default bottom component
     * @return {Node} */
    defaultlistfooter = () = {
        return (
            <flexview justify= "Center" align= "center" style={styles.listfooterview}>
                {this.defaultlistfootercontent ()}
            </FlexView>
        );
    }
/**
     * Content at the bottom of the list
     * @return {Node}
     *
    /defaultlistfootercontent = () = {
        Const {isend, refreshing, I Snotlist, isError} = this.state;
        if (isnotlist) {
            return (
                <_Text> does not query the relevant data. </_Text>
            );
        }
        if (isend) {
            return [
                <flexitem style={styles.listfooterline} key={1}/>,
                <_text key={2}> No more data </_text>,
                <flexitem style={styles.listfooterline} key={3}/>,
            ];
        }
        if (refreshing) {
            return (
                <_Text> loading ...</_text>
            );
        }
        if (isError) {
            return (
                <_Text> query failed, drop-down reload. </_Text>
            );
        }
        Return (
            <_Text> pull load more </_Text>
        );
    }
Note: The layout of your feet can be changed according to your project requirements.

13.listemptycomponent={this.renderlistempty} empty layout, no data, request error display, code is as follows:

/**
     * The component displayed when the list is empty
     * @return {reactcomponent} */
    renderlistempty = () = {
        return (
            <view >
                <Text> no data Oh. </Text>
            </View>
        );
    }

14.ref={ref = This._listref = ref} Current instance OK, summary is here, follow-up I will summarize more use of components ~ ~

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.