Using Deviceeventemitter to solve the problem of linkage between title bar and data list

Source: Internet
Author: User
Tags constant constructor emit

Analysis

The page contains the titlebar and Tabnavigator components, while Tabnavigator contains three messagescreen components, and Messagescreen components in Flatlist, The item is a custom Messageitem component. So nesting level is still quite a lot of. To achieve the effect in the animation, you need to click the Edit button in the titlebar to refresh the Messageitem state. The deviceeventemitter relatively simple point is used here.

Of course, if there is a better way to welcome communication. Source Code

Messagewrapperscreen.js

Import React from ' React ';
Import {StyleSheet, Text, View, Toastandroid, Backhandler, Deviceeventemitter, pixelratio} from ' react-native ';
Import {Tabnavigator} from ' React-navigation '; Import TitleBar from ".
/components/titlebar ";
Import Messagescreen from "./messagescreen"; Import Theme from ".
/style/theme "; Import Constant from ".
/constant "; Import Bottombutton from ".

/components/bottombutton "; Const Messagenavigator = Tabnavigator ({Tab1: {screen:messagescreen, navigationoptions: ({navigation}) = = (
  {tabbarlabel: ' All Messages '})
  }, Tab2: {screen:messagescreen, navigationoptions: ({navigation}) = ({tabbarlabel: ' Sales operation notification '}) 
  }, Tab3: {screen:messagescreen, navigationoptions: ({navigation}) = ({tabbarlabel: ' Small Secretary notice '}) }}, {lazy:true, tabbaroptions: {activeTintColor:theme.activeColor, InactiveTintColor:theme.inactiveCo Lor, Uppercaselabel:false, LabelStyle: {fontsize:12,
      margintop:0, Marginbottom:0,}, Indicatorstyle: {BackgroundColor:theme.activeColor},

Style: {backgroundcolor: ' #FFF ', Height:35,},},}); /** * Station Letter tab Outer page (including tabnavigator) */export default class Messagewrapperscreen extends React.component {constructor (p  Rops) {super (props) This.state = {isediting:false,//is being edited}} render () {Const NAVIGATION =
    This.props.navigation; 
          Return (<view style={styles.container}> <titlebar nav={navigation} title= "Station letter" Righttext={this.state.isediting?
        "Cancel": "Edit"} Handlerightclick={this.handleedit} Handlebackclick={this.handlebackclick}/> <messagenavigator navigation={navigation}/> {this.state.isEditing?
              (<view style={{flexdirection: ' Row ', height:40}}> <bottombutton title= "all read" handleclick={this.handleallread}/> <view style={{width:1/pixelratio.get (), height:40, Backgroundcolo
            R: ' White '}}/> <bottombutton title= ' delete ' Handleclick={this.handledelete}
  /> </View>): null} </View>);
    } Handleedit = () = {this._updatemessagelist ();
  This.setstate ({isediting:!this.state.isediting});

  };
      Handlebackclick = () = {if (this.state.isEditing) {this._updatemessagelist ();
    This.setstate ({isediting:false,});
    } else {this.props.navigation.goBack ();

  }
  }; /** * Send * @private */_updatemessagelist = () = {Deviceeventemitter.emit (constant.event_update_messag E_list,!this.state.isediting);

  Monitor};

  Handleallread = () = {toastandroid.show (' handleallread ', Toastandroid.short)}; Handledelete = () = {toastandroid.show (' HandlEdelete ', Toastandroid.short)}} Const Styles = Stylesheet.create ({container: {flex:1, flexdirection: ' Co 
    Lumn '}, Button: {color: ' White ',}, Buttonwrapper: {flex:1, paddingleft:10, Paddingright:10,
    Justifycontent: ' Center ', Alignitems: ' Center ', BackgroundColor:theme.activeColor,}, Btncontainer: {

Flex:1,}}); https://reactnavigation.org/docs/intro/nesting messagewrapperscreen.router = Messagenavigator.router;

Extension: "Resolving navigator nesting issues in Reactnavigation"

Messagescreen.js

Import React from ' React ';

Import {StyleSheet, View, Flatlist, Activityindicator, Toastandroid,} from ' react-native '; Import Loadingview from ".
/components/loadingview "; Import Messageitem from ".
/components/messageitem "; Import {requestmessagelist} from ".

/request/apis ";
    Export default class Messagescreen extends React.component {constructor (props) {super (props);
    This.page = 1;
      This.state = {first:false,//First load, does not render flatlist Refreshing:false, Loadmore:false, dataList: [], 
    Isediting:false,}} componentdidmount () {//This.requestdata (1)} _onpressitem = (msgId) = {
    const {Navigate} = this.props.navigation;
    Console.log (this.props.navigation);

  Navigate (' Messagedetails ', {' msgId ': MsgId})}; _renderitem = (item, index) = = (<messageitem editable = {this.state.isEditing} Data={item} on

  Pressitem={this._onpressitem}/>); _dividerline = () = (&Lt

  View style={{height:2}}/>);

  _emptycomponent = () = (<LoadingView/>);
    _onrefresh = () = {this.setstate ({refreshing:true});

  This.requestdata (1)};
        _onendreached = () = {if (!this.state.refreshing &&!this.state.loadmore) {this.setstate ({
      Loadmore:true});
    This.requestdata (++this.page);

  }
  }; _onfootercomponent = () = {return this.state.loadMore?
          (<view style={styles.footerstyle}> <activityindicator Style={styles.indicatorstyle}

  Size= "large"/> </View>): null};
        RequestData = () = {requestmessagelist (). then (Result) = {This.setstate ({first:false, Loadmore:false, refreshing:false, dataList:this.page = = 1? Result.data:this.state.dataList.concat (Result.data),})}, (Error) = {This.setstate ({First
      : false,  Loadmore:false, Refreshing:false,});
    Toastandroid.show ("error", Toastandroid.short);
  });

  };

    Render () {Let content;
    if (this.state.first) {content = (<LoadingView/>); } else {content = (<flatlist initialnumtorender={10} data={this.state.datalist} Keyextra
        ctor={(item, index) = Item.relationid} Renderitem={this._renderitem} Onrefresh={this._onrefresh} Refreshing={this.state.refreshing} Itemseparatorcomponent={this._dividerline} onendreachedthreshold={0.
    1} onendreached={this._onendreached} listfootercomponent={this._onfootercomponent}/>);
  } return (<view style={{flex:1}}> {content} </View>); }//Render () {//return (<View/>)//}} Const STYLES = Stylesheet.create ({footerstyle: {height:5 0, Alignitems: ' Center ', justifycontent: ' Center ', backGroundcolor: ' #DDD '}, Indicatorstyle: {height:40, Alignitems: ' Center ', justifycontent: ' Center '}}) ;

messageitem.js

Import React from ' React '; Import {StyleSheet, View, Text, Touchablenativefeedback, Image, Dimensions,deviceeventemitter, toastandroid} from ' Reac

T-native ';
Import moment from ' moment ';
Import CheckBox from './checkbox '; Import Constant from ".

/constant ";
    Export default class Messageitem extends React.component {constructor (props) {super (props); This.state = {checked:false, Isediting:false,}} _onpress = () = {Const ITEM = This.prop
    S.data.item;
  This.props.onPressItem (Item.relationid);

  }; 
      Componentwillmount () {This.listener = Deviceeventemitter.addlistener (Constant.event_update_message_list, (e) + = {
    This.setstate ({isediting:e});
  });
  } OnChange = (checked) = {this.setstate ({checked:!this.state.checked,});

  };
  Componentwillunmount () {this.listener.remove ();
    } render () {Const ITEM = This.props.data.item; Const TIME = Moment (item.gmtcreate). formaT (' yyyy-mm-dd '); Return (<touchablenativefeedback onpress={this._onpress} background={touchablenativefeedback.rip
            ple (' #CCC ', false)}> <view style={styles.itemcontainer}> {this.state.isEditing? (<view style={{marginright:5}}> <checkbox label= "CHECKED={THIS.S
          tate.checked} Onchange={this.onchange}/> </View>): null}  <view style={{flex:1}}> <view style={styles.itemtitlecontainer}> <view Style={{flexdirection: ' Row ', Alignitems: ' Center ', flexshrink:1,}}> {item.isread = = 0? <view sty le={styles.dot}/>: null} <text Style={styles.titlestyle} numberoflines={1}>{item.title}</text > </View> <text style={[styles.contentstyle, {flexshrink:0}]}>{time}</text&
Gt            </View> <text Style={[styles.contentstyle, {margintop:6}]} NUMBEROFLINES={2}&GT;{ITEM.S
  ummarize}</text> </View> </View> </TouchableNativeFeedback>); }} Const Styles = Stylesheet.create ({itemcontainer: {flexdirection: ' Row ', Alignitems: ' Center ', Backgro Undcolor: ' #FFF ', Padding:8,}, Itemtitlecontainer: {flexdirection: ' Row ', justifycontent: ' Space-betwee
  n ',}, TitleStyle: {fontsize:15, color: ' #222 ',}, Contentstyle: {fontsize:13, color: ' #BBB ', }, Dot: {width:6, Height:6, Borderradius:3, backgroundcolor: ' #FF0000 ', Marginright:3},}) ;
Core Code

Add a time listener to Messageitem and remove the listener after the component has been uninstalled

  Componentwillmount () {
    This.listener = Deviceeventemitter.addlistener (
      constant.event_update_message_list , (e) = = {
      This.setstate ({
        isediting:e});}
    )
  ;

  Componentwillunmount () {
    this.listener.remove ();
  }

Click the Edit button to trigger the event

Deviceeventemitter.emit (
    constant.event_update_message_list,!this.state.isediting);//Hair monitoring

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.