Slow Cow Series three: React native practice

Source: Internet
Author: User



The last time I released my slow bull stock app, there is a bit of feedback from the park friends, the app is based on Sencha Touch + Cordova Development, Sencha itself is a relatively heavy framework, in chrome running performance is good, But in the Android WebView, the performance is limited to the machine configuration, in my millet 2s performance is OK, in the Millet 4s open more fluent, but the Android model is too diverse than iOS, Sencha touch in iOS performance is good, But I haven't compiled the iOS version yet.



Later I tried to use the next Ionic framework, based on the development of ANGULARJS, the framework to light, in the public number of slow bull stock to try to develop a few pages, feel very good, originally wanted to use Angularjs to re-do an app, but then contacted React Native, Try to use the next, React native programming experience similar to Sencha Touch, complete components, JSX syntax is very interesting, gradually accustomed to use it is also very handy.



Interested friends can compare these three options, I left this three options:



Slow Bull stock app (Sencha touch+ Cordova) solution






Slow Bull public number (ionic scheme)






Demo (React native solution)



Animation:






React native compared to the above two, the experience smoother, of course, the native application is certainly better than in the WebView experience, Reactnative combines the advantages of native development and web development, but React native now support Android is not too good, Like animations.



Reactnative Flex Layout, component thinking is very good, get started quickly, but because the final display is the original, so still want to know more about the development of the original, if necessary, do the bridge, such as I do the candlestick chart, struggling to find the relevant components, only the bridge connected to the Mpandroidchart.



The demo mainly implements several key functions that I think are more important:



1. Navigation



2. List



3. Drop-down Refresh



4. Chart



After the implementation of these functional points, the subsequent work is much easier, such as form submission, third-party login, settings and so on pages.



Here are some of the ways to implement these points,



1. Navigation :



Side- slip menu :



Familiar with the native development of the students to know that this is the original isDrawerLayout,Bridge through RN,very slippery, very smooth, before using CSS3 in the WebView to do a side-slip menu, of course, compared to this!



page Switching :



Using the Navigator component of RN, this component implements a stack, each time a new page is moved to the stack to push new UI navigation information, and then when render to determine which UI component to display, this navigation component will move the historical UI outside the visual range, Using opacity to set the UI to transparent, and then to absolutely navigate beyond the viewable range, return, and then the history of the UI to move the visual range, so that the state of the history UI is still maintained, such navigation on the Web can also be used for reference.



This navigation can also set the transition animation, to see the source code, is really a lot of implementation of the animation, including Pushfromright,floatfromright,fadeandroid, but does not work after Setup, only fadeandroid have effect, but the animation flashed over , not smooth, the support for Android here is not very good, or where I set the wrong?



tab Toggle :



tab switching is easier to do, but one thing, in the process of page switching, do not re-render each tab corresponding to the content, re-render will clear the current state of the page, such as the position of the scroll bar, and poor performance, for reference Navigator, Move the non-focused tab page outside the viewable range.



The icon of the button in the demo is vector, the advantage of the icon font is needless to say, the native system can also use the icon font, the students do not like to use pictures is a good news, a thought to do so many pictures, to consider each resolution, on the mind Wow, Here is an open source component react-native-icons on GitHub.



Paste Snippet Code:


render: function() {
    var navigationView = (
      <SideMenu onItemSelected={this.onItemSelected}/>
    );
    return (
      <DrawerLayout
        ref="drawerMenu"
        drawerWidth={300}
        drawerPosition={DrawerLayout.positions.Left}
        renderNavigationView={() => navigationView}>  
          <Navigator
            ref=‘navigator‘
            debugOverlay={false}
            style={styles.appContainer}
            configureScene={(route) =>Navigator.SceneConfigs.FloatFromRight}
            initialRoute={{name:‘main‘,component:(<TabPanel/>)}}
            renderScene={(route, navigator) => {          
                return (route.component);
            }}
          />
      </DrawerLayout>
);


2. List:



I implemented a list of stocks in the demo, and the list was split into list components and ListItem components, and it was important to use react to develop a component, which was the same experience with Sencha.



List here does not use the ListView component, is the ScrollView package a listttem list, if the amount of data is larger, or more complex list, you can use the official ListView to do, performance will be better, each update will only update the changed list items, also provides a classification, Set the header and footer, and so on.



Paste Snippet Code:


 createRows:function(){
    return  this.state.myStockList.map(function (obj) {
      return (<StockItem key={obj.code} id={obj.code} data={obj}></StockItem>);
    });
  }, 
  render: function() {
    return (
       <SwipeRefreshLayout 
          ref={(control)=>{this._view=control}} 
          style={styles.scrollView} 
          onRefresh={this.reloadData}>   
            <ScrollView style={{flex:1}}>
              {this.createRows()}
            </ScrollView>
        </SwipeRefreshLayout>
    );
  }





3. Drop-down refresh:



On GitHub, there are a number of drop-down refresh components, such as; React-native-gifted-listview, but all iOS can be pulled down, there is a bug on Android, the document explains:


Pull-to-refresh in Android (tried to implement it's it seems that onresponderrelease event are not catchable yet in Andro ID listview-react-native


about how to respond to the gesture in Rn, I do not know how to understand, after more animation aspects of the study, because of the understanding of the native control of the bridge, all lazy, the original swiperefreshlayout control to do the bridge, package on the ScrollView, you can implement the drop-down refresh, In the JS in response to the swiperefreshlayout sent by the refresh event, while opening a closed flush interface, JS end to get the data update, turn off the refresh state.



4. Chart





Chart here, I spend the most time, is not very perfect, but can show the candlestick, but in the interaction or to strengthen.



Before the web has done two candlestick chart, one is Sencha, one is D3, after using RN, before the chart is not used, but also consider a set of WebView, with D3 to do, but the effect is certainly not good wow, finally learned the native development, learning the layout of the native UI, Component inheritance architecture, learning how to use Mpandroidchart components, how to bridge native components and so on, harvest is not small, now open Android Studio, open sublime side ...



Native components, view is the base class for all UI components, and ViewGroup is a container for these components, which itself is derived from view, RN provides two types of Viewmanager classes to bridge these two types of components, Viewmanager management component creation, layout, As well as property settings, event triggering.



Paste Snippet Code:



Android Side (bridging chart snippet):


public class MPBarLineChartManager extends SimpleViewManager<BarLineChartBase> {
    private String CLASS_NAME="MPBarChart";
   
    @Override
    public String getName() {
        return this.CLASS_NAME;
    }

    @Override
    protected BarLineChartBase createViewInstance(ThemedReactContext reactContext) {
        BarChart chart=new BarChart(reactContext);
        return  chart;
    }

    @ReactProp(name="touchEnabled",defaultBoolean = true)
    public void setTouchEnabled(BarLineChartBase chart,boolean enable){
        chart.setTouchEnabled(enable);
    }
   ......
}


JS End:


var { requireNativeComponent,PropTypes } = require(‘react-native‘);

var iface = {
  name: ‘BarChart‘,
  propTypes: {
  	data:PropTypes.object,
  	touchEnabled:PropTypes.bool,
  	......
	scaleX: PropTypes.number,
	scaleY: PropTypes.number,
	translateX: PropTypes.number,
	translateY: PropTypes.number,
	rotation: PropTypes.number,
  },
};

module.exports = requireNativeComponent(‘MPBarChart‘, iface);


  



The bridging project for this diagram I posted on GitHub, currently implements the bridging of histograms, line graphs, and combo charts.



Https://github.com/hongyin163/react-native-mpchart



There is hope that the students can use the chart, if you can continue to help enhance it better!






After learning to bridge the native components, I was caught in a pattern, as long as the difficulty in the RN, I would like to bridge a native Android components, although it is not very good to know, because if too many native components, the subsequent migration trouble, Of course, it is best to take advantage of the official Android and iOS support components, preferably in a platform-independent way to do, here is the biggest feeling is that RN provides a way to allow JS to interact with the native components, business logic written in JS, the use of native components presented, if the original development of the classmate support, So the use of RN development is much more convenient, provide a consistent component library, a set of code can be run on two systems, so it is not just learn once write anywhere.






About Performance Optimizations:



1. Delayed loading



If too many components are loaded at one time, RN needs to wait for all components to render complete before it is displayed, there will be white screen, all of the components are best to be less each time, such as the framework of building the page, frame rendering after the completion of loading data, create data-based components, or the use of settimeout delay loading other components.



2. Using Setnativeprops



React the component as a state machine, usually using the SetState method to change the state of the component, the page will be re-rendered, but the rendering performance is poor, Setnativeprops can bypass the process, directly modify the native component properties, or invoke the native component of the API, Performance is much better, but the state of synchronization will be considered more.



3. Implement Shouldcomponentupdate method



React will have a diff algorithm when the component is rendered, and if the virtual DOM state changes, the component will be re-rendered, and if the Shouldcomponentupdate method is implemented, returning false will avoid unnecessary diff calculations and rendering.






About react, this article has spoken of his previous life, written very well: a shortcut to the full stack of engineers--react



React is really ubiquitous, react-dom,react-canvas,react-native, looks promising wow!



Finally, you can focus on the public number of the slow bull stock:



Send react, can get demo apk file, install experience.





The source of this project will be submitted to GitHub, the article written in general, forgive me! You are welcome to comment on ^_^



About my part-time entrepreneurial journey



Slow Bull Series One: How to crawl stock data



Slow series two: front-end technology selection



Slow Cow Series three: React native practice


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.