reactNative移动开发技术前沿React Native开发经验集

初识ReactNative

2017-02-21  本文已影响197人  45b645c5912e

公司打算用react-native开发APP,初始RN遇到了很多坑,搭建了一个小的项目框架,结合redux根据公司现成的接口写了几个小demo,接触前端半年多,之前是做iOS的,感觉转起来很困难,希望有大神可以给出些优化的建议!

项目介绍

项目启动流程

<!DOCTYPE html>
<meta charset="utf-8">
<title>React Native for Web</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<div id="react-root"></div>
<script src="/bundle.js"></script>
import React, { Component } from 'react';
import { Provider } from 'react-redux';
import App from './containers/App';
import configureStore from './store/configureStore';
class Root extends Component {
  render() {
    return (
      <Provider store={configureStore()}>
        <App />
      </Provider>
    );
  }
}
export default Root;
import React, {Component} from 'react';
import { Navigator } from 'react-native';
import MainTabsView from './MainTabsView';
import BroswerView from './BroswerView';
import LoginView from './LoginView';
import CarDetailView from './CarDetailView'
import FindCarView from './FindCarView'
import FreePriceView from './FreePriceView'
import CarLifeView from './CarLifeView'
import SpecialCarView from './SpecialCarView'
const ROUTES = {
  main_tabs_view: MainTabsView,
  login_view:LoginView,
  broswer_view: BroswerView,
  car_detail_view:CarDetailView,
  find_car_view:FindCarView,
  free_price_view:FreePriceView,
  car_life_view:CarLifeView,
  special_car_view:SpecialCarView,
}
class App extends Component {
  renderScene = (route, navigator) => {
    let Scene = ROUTES[route.name];
    console.log("app renderscene");
    switch (route.name){
      case 'main_tabs_view':
        return <Scene navigator={navigator} tab={2}/>;
      case 'login_view':
        return <Scene navigator={navigator}/>;
      case 'broswer_view':
        return <Scene
          url={route.url}
          navigator={navigator}/>;
      case 'car_detail_view':
        return <Scene {...route.params} navigator={navigator}/>;
      case 'find_car_view':
        return <Scene navigator={navigator}/>;
      case 'free_price_view':
      return <Scene navigator={navigator}/>;
      case 'car_life_view':
        return <Scene navigator={navigator}/>;
      case 'special_car_view':
        return <Scene navigator={navigator}/>;
    }
  }
  configureScene = (route, routeStack) => {
    switch (route.name){
      default:
            return Navigator.SceneConfigs.PushFromRight;
    }
  }
  render() {
    return <Navigator
      initialRoute={{name: 'login_view'}}
      renderScene={this.renderScene}
      configureScene={this.configureScene}/>
  }
}
export default App;

效果展示

componentDidMount() {
    this.props.actions.getBannerSource({});
    this.props.actions.getHotCarSource({});
    this.props.actions.getFreePriceListSource({});
    this.props.actions.getCarShowBannerSource({});
    this.props.actions.getSpecialCarSource({});
  }
//轮播图
export function getBannerSource(item) {
    console.log("getBannerSource");
    return dispatch => {

        //dispatch(requestPosts(item));
        return fetch(API_BASE_URL+'/mobile/ad/findAllShowAdByMobile', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'sessionid': "hanwuqia"
            },
            body: JSON.stringify({"query":{"pagenum":10,"page":1}})
        })
            .then((response) => response.json())
            .then((responseJson) => {
                //console.log(responseJson);
                if(responseJson.code == 0){
                    dispatch(receiveBannerPosts(responseJson.data.rows));
                }

            })
            .catch((error) => {
                console.error(error);
            });
    }
}
function receiveBannerPosts(banner, json) {
    return {
        type: DATA_BANNER,
        banner,
    }
}
export default function secondView(state ={
    banner: [],
}, action) {
    switch (action.type) {
        case types.DATA_BANNER :
            return Object.assign({}, state, {
                banner: action.banner
            });
        default:
            return state
    }
}
function mapStateToProps(state) {
  return {
    banner: state.secondView.banner,
  };
}
function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(Actions, dispatch)
  }
}
export default connect(
    mapStateToProps,
    mapDispatchToProps
)(SecondView);
render() {
    const {  banner ,hotCarList,freePriceList,carShowBanner,specialCar,navigator} = this.props;
    return (
        <View style={{ flex: 1, backgroundColor:'#EBEBEB'}}>
            <TitleBar title="react-native-mobile"></TitleBar>
            <ScrollView >
                <Banner banner={banner}></Banner>
                <ToolBar navigator={navigator}></ToolBar>
                <Text style={styles.title}>免费看低价</Text>
                <FreePriceList  navigator={navigator} freePriceList={freePriceList}></FreePriceList>
                <Text style={styles.title}>车主秀</Text>
                <CarShowBanner carShowBanner={carShowBanner}></CarShowBanner>
                <Text style={styles.title}>热门推荐</Text>
                <HotCarList hotCarList={hotCarList} navigator={navigator}></HotCarList>
            </ScrollView>
        </View>
    )
  }
首页
首页
render(){
        const { brand} = this.props;
        var  Arr = brand ,
            sectionIDs =[],//所有区ID的数组
            rowIDs =[];//行ID数组
        for (let i in brand ) {
            sectionIDs.push(i);
            rowIDs.push(brand[i])
        }
        return(
                <ListView//创建表,并设置返回section和cell的方法
                    dataSource={this.dataSource.cloneWithRowsAndSections(Arr,sectionIDs,rowIDs)}
                    renderRow={this.renderRow}
                    renderSectionHeader={this.renderSectionHeader}
                    renderHeader={this.renderHeader }
                />
        )
    }
//返回头部视图
    renderHeader(){
        var rowWidth = screenWidth/5;
        return(
            <View  style={{width:screenWidth,flexDirection:'row',flexWrap:'wrap',height:160}}>
                {
                    this.hotBrndArr.map((dic, i) => <TouchableOpacity key={i} style={{width:rowWidth,height:80}} onPress={() => {
                                    this.selectBrand(dic)}}>
                        <View  style={{backgroundColor:'white',justifyContent:'center',alignItems:'center',width:rowWidth,height:80}}>
                            <Image style={styles.imageStyle} source={{ uri: dic[1]}}/>
                            <Text>{dic[2]}</Text>
                        </View>
                    </TouchableOpacity>)  // 单行箭头函数无需写return
                }
            </View>
        )
    }
    //返回cell的方法
    renderRow(rowData,sectionID,rowID,highlighRow){
        return(
            <TouchableOpacity key={rowID} onPress={() => {
                                    this.selectBrand(rowID)}}>
                <View style={styles.cellStyle}>
                    <Image style={styles.imageStyle} source={{ uri: rowID[2]}}/>
                    <Text style={{marginLeft:20}}>{rowID[1]}</Text>
                </View>
            </TouchableOpacity>

        )
    }

    //返回section的方法
    renderSectionHeader(sectionData,sectionID){

        return(
            <View style={styles.sectionStyle}>
                <Text style={{marginLeft:10}}>{sectionID}</Text>
            </View>
        )
    }
找车
<Drawer
                    side="right"
                    type="overlay"
                    ref={(ref) => this._drawer = ref}
                    content={...}
                    tapToClose={true}
                    openDrawerOffset={0.2}
                    tweenHandler={(ratio) => ({main: { opacity:(2-ratio)/2 }})}
                    onClose={()=>{this.maskDidClose()}}
                    styles={{
                            drawer: { shadowColor: '#000000', shadowOpacity: 0.5, shadowRadius: 3},
                            main: {backgroundColor:"#EBEBEB"},
                    }}
                >
closeControlPanel = () => {
        this._drawer.close()
    };
    openControlPanel = () => {
        this._drawer.open()
    };
找车筛选
render(){

        const { car,isRefreshing} = this.props;

        return(
            <ListView //创建ListView
                dataSource={this.dataSource.cloneWithRows(car)} //设置数据源
                renderRow={this.renderRow} //设置cell
                contentContainerStyle={styles.listViewStyle}//设置cell的样式
                onEndReached={ this._toEnd }
                onEndReachedThreshold={10}
                renderFooter={ this._renderFooter }
                enableEmptySections = {true}
                removeClippedSubviews={false}
                refreshControl={
                        <RefreshControl
                            refreshing={isRefreshing}
                            onRefresh={this._onRefresh}
                            tintColor="gray"
                            title="Loading..."
                            titleColor="gray"
                            colors={['#ff0000', '#00ff00', '#0000ff']}
                            progressBackgroundColor="#ffff00"
                        />}
            />)
    }
refreshControl={
                        <RefreshControl
                            refreshing={isRefreshing}
                            onRefresh={this._onRefresh}
                            tintColor="gray"
                            title="Loading..."
                            titleColor="gray"
                            colors={['#ff0000', '#00ff00', '#0000ff']}
                            progressBackgroundColor="#ffff00"
                        />}
constructor(props) {
        super(props);
        //返回cell样式的方法
        this.renderRow = this.renderRow.bind(this);
        //下拉刷新的方法
        this._onRefresh = this._onRefresh.bind(this);
        //上滑刷新的方法
        this._toEnd = this._toEnd.bind(this);
        //返回底部视图的方法
        this._renderFooter = this._renderFooter.bind(this);
      //数据源初始化
        this.dataSource = new ListView.DataSource({
            rowHasChanged: (row1, row2) => row1 !== row2
        });
    }
免费看低价
免费看低价筛选
render(){
        const {data,refresh,actions}=this.props;

        return(

            <ScrollableTabView  style = {{width:screenWidth,height:screenHeight-64,backgroundColor:'#EBEBEB'}}
                                initialPage={0}
                                tabBarTextStyle={{fontSize: 14}}
                                tabBarUnderlineStyle={{backgroundColor: 'orange'}}
                                tabBarInactiveTextColor = "#999999" tabBarBackgroundColor = "white" tabBarActiveTextColor = "#333333"
                                onChangeTab={(obj) => this.changeTab(obj)}
            >
                <CarLifeList tabLabel='全部' actions={actions} pid={2} index={0} refresh ={refresh} dataArr={data}></CarLifeList>
                <CarLifeList tabLabel='新车' actions={actions} pid={2} index={1} refresh ={refresh} dataArr={data}></CarLifeList>
                <CarLifeList tabLabel='装饰' actions={actions} pid={2} index={2} refresh ={refresh} dataArr={data}></CarLifeList>
                <CarLifeList tabLabel='改装' actions={actions} pid={2} index={3} refresh ={refresh} dataArr={data}></CarLifeList>
                <CarLifeList tabLabel='自驾' actions={actions} pid={2} index={4} refresh ={refresh} dataArr={data}></CarLifeList>

            </ScrollableTabView>
        )
           
    }
//通过loading 的改变刷新
case types.CAR_SHOW_FETCH :
            return Object.assign({}, state, {
                carShowDataArr: action.carShowDataArr,
                loading:action.loading
            });
requestAnimationFrame(() => {
            this.setState({
                selectInteriorColor :index,
            });
            const {  interiorColorList,exteriorColorList,actions ,id,detailType} = this.props;
            let inId = interiorColorList[index].id;
            let outId = exteriorColorList[this.state.selectExteriorColor].id;
            actions.getCarInfo({outId,inId,id,detailType});
 });
车款详情

性能优化

onstructor(props) {
        super(props);
        this.state={

            renderPlaceholderOnly:true,
        }
    }
render() {
        if (this.state.renderPlaceholderOnly) {
              //loading页
            return this._renderPlaceholderView();
        }
        return (     
               //界面
        )
    }
_renderPlaceholderView() {
        return (
            <View style={{flex:1,backgroundColor:'white',justifyContent:'center',alignItems:'center',}}>
                <Text>Loading...</Text>
            </View>
        );
    }
componentDidMount() {

        InteractionManager.runAfterInteractions(() => {
            this.setState({renderPlaceholderOnly: false});
            this.props.actions.getBrandSource({});
            this.props.actions.getCarTypesource();

        });

    }
上一篇 下一篇

猜你喜欢

热点阅读