ReactNative 開發(fā)總結(jié)

項(xiàng)目使用 rn 開發(fā)接近尾聲,將遇到的問(wèn)題記錄一下,對(duì)應(yīng)一些實(shí)用場(chǎng)景。

setState

一定要注意 setState 是異步的。

如果要在setState后進(jìn)行某些操作,

this.setState({
            data: []
        },()=>{
            // some function
})

setState后,并不會(huì)立即更新 UI。

this.setState({data1: 1})
this.setState({data2: 2})
this.setState({data3: 3})
等價(jià)于
this.setState({
    data1: 1,
    data2: 2,
    data3: 3
})

項(xiàng)目結(jié)構(gòu)

使用 react-navigation(V2),

RootStack

----AdScene

----IntroScene

----RootTab

--------HomeStack

--------MyStack

--------SettingStack

----GestureLock

    ...

對(duì)應(yīng)代碼

const Scene = {
    WebView: WebView,
    MomentScene: MomentScene,
    QrCodeScene: QrCodeScene
}

const HomeStack = createStackNavigator({
    Home: Home,
    ...Scene,
});

const MyStack = createStackNavigator({
    MyScene: MyScene,
    ...Scene
});

const SettingStack = createStackNavigator({
    SettingStack: SettingStack,

    ...Scene
});

const RootTab = createBottomTabNavigator({
    Home: HomeStack,
    MyScene: MyStack,
    Setting: SettingStack,
});

const RootNav = createStackNavigator({
    AdScene: AdScene,
    RootTab: RootTab,
    Login: Login,
    Intro: Intro,
    GestureLock: GestureLock,
}, {
    headerMode: 'none',
    mode: 'modal'
});


export default class App extends Component {
    render() {
        return <RootNav/>
    }
}

定義全局導(dǎo)航

在 ChildComponent中可以使用 withNavigation,通過(guò) this.props.navigation 來(lái)取得當(dāng)前 router,為了更方便地跳轉(zhuǎn),還是定義一個(gè)通用的路由方式比較好。

NavigationService.js

import { NavigationActions } from 'react-navigation';

const config = {};

export function setNavigator(nav) {
    if (nav) {
        config.navigator = nav;
    }
}

export function navigate(routeName, params) {
    if (config.navigator && routeName) {
        const action = NavigationActions.navigate({ routeName: routeName, params: params });
        config.navigator.dispatch(action);
    }
}

export function goBack() {
    if (config.navigator) {
        const action = NavigationActions.back({});
        config.navigator.dispatch(action);
    }
}

App.js 中

import {setNavigator} from './NavigationService'
export default class App extends Component {

    componentDidMount() {
        setNavigator(this.navigator);
    }

    render() {
        return <RootNav ref={nav => { setNavigator(nav); }}/>
    }
}

定義通用方法

import {navigate} from './NavigationService'

class Utils {
    static navigateTo(scene, params){
        navigate(scene, params)
    }
}

然后就可以使用 Utils.navigateTo('WebView', {url: 'https://www.github.com'})愉快地跳轉(zhuǎn)了。

開屏廣告頁(yè)的實(shí)現(xiàn)

基本思路:廣告頁(yè)設(shè)為應(yīng)用首屏,展示完廣告頁(yè)后,重設(shè) RootTab 為首屏

react-navigation v1版本跟 v2版本是有區(qū)別的,下面是 v2 版重設(shè)方法

_dismiss(){
        const fun =  StackActions.reset({
            index: 0,
            actions: [NavigationActions.navigate({ routeName: 'RootTab' })],
        })
        this.props.navigation.dispatch(fun)
}

啟動(dòng)應(yīng)用—讀取廣告頁(yè)緩存—如果圖片有緩存則顯示、沒(méi)有就直接進(jìn)入首頁(yè)。

最后實(shí)現(xiàn)起來(lái)還是有一點(diǎn) Bug,使用 AsyncStorage,由于讀取是異步的,如果不顯示廣告頁(yè)(圖片沒(méi)緩存或者接口控制不顯示),還是會(huì)停留一小段時(shí)間。

手機(jī)號(hào)碼輸入格式化

<TextInput ref='textInput' 
           style={styles.field}
           placeholder={'手機(jī)號(hào)'}
           keyboardType='phone-pad'
           value={this.state.mobile}
           maxLength={13}
           underlineColorAndroid={'transparent'}
           onChangeText={(text)=>{
               if(text.length == 3 && this.state.mobile.length == 2){
                   text += ' '
               }else if(text.length == 3 && this.state.mobile.length == 4){
                   text = text.substring(0 , text.length-1)
               } else if(text.length == 8 && this.state.mobile.length == 7){
                   text += ' '
               }else if(text.length == 8 && this.state.mobile.length == 9){
                   text = text.substring(0 , text.length-1)
               }
               this.setState({mobile: text})
           }}
/>

注意,在Android中TextInput控件默認(rèn)會(huì)有下劃線,使用 underlineColorAndroid={'transparent'}可去除;并且一定要設(shè)置value屬性,否則Android中,輸入文字后輸入框不會(huì)相應(yīng)改變。

文字間距lineHeight

text: {
        fontSize: 14,
        lineHeight: 20,
        width: '90%'
    }

使用index

為了使用方便,可以在相似模塊目錄下定義 index,如下圖:

index.png

這樣就可以通過(guò) import {Utils, CheckFlow} from './util使用方法

children屬性

component 默認(rèn)都有一個(gè)children屬性

children: PropTypes.oneOfType([
            PropTypes.string,
            PropTypes.node,
            PropTypes.element
        ])

<CustomeComponent>some</CustomeComponent>

export default class CustomeComponent extends Component {
    render() {
        var text = this.props.children // some
        return (
            <View/>
        )
    }
}

條件渲染 renderIf

import renderIf from 'render-if'

 return (<View style={styles.container}>
    {renderIf(this.state.shouldRender)(
        <Text style={{paddingTop: 10, color: 'red'}}>example</Text>
    )}
 </View>)

單例的實(shí)現(xiàn)

export default class UserManager{

    static shared = null;

    _userInfo = null

    static getInstance() {
        if (UserManager.shared == null) {
            UserManager.shared = new UserManager();
        }
        return UserManager.shared;
    }
    
   getUserInfo() {
        if (this._userInfo){
        } else {
            Storage.getInstance().getObject(Constants.userInfokey).then((data)=>{
                this._userInfo = data
            })
        }
        return this._userInfo;
    }

    setUserInfo(key) {
        this._userInfo = key;
        Storage.getInstance().saveObject(Constants.userInfokey, key).then(()=>{
            console.log('save userInfokey success')
        });
    }
}


UserManager.getInstance().getUserInfo()

Fetch 并行請(qǐng)求

開發(fā)中偶爾遇到需要請(qǐng)求多個(gè)接口,一起處理返回結(jié)果。
fetch api 是基于 promise 的,可以很方便地實(shí)現(xiàn)這個(gè)需求

Promise.all([
  fetch("api1"),
  fetch("api2"),
  fetch("api3")
]).then(([result1, result2, result3]) => {
    // result
}).catch((err) => {
    console.log(err);
});

一般會(huì)對(duì) fetch 進(jìn)行簡(jiǎn)單的封裝,只要返回 promise 對(duì)象就好了。


export default class FetchUtils  {
    static post(url, data={}) {
    
        let request = this._generateRequest(url, data)

        return new Promise((success, error)=> {fetch(request).then((response) => response.json())
            .then((jsonData) => {
                success(jsonData)
            })});
    }
}

Promise.all([
  FetchUtils.post("api1"),
  FetchUtils.post("api2"),
  FetchUtils.post("api3")
]).then(([result1, result2, result3]) => {
    // result
}).catch((err) => {
    console.log(err);
});

react-navigation android 導(dǎo)航欄標(biāo)題居中

react-navigation(v2.2.0) 并沒(méi)有為 android 提供類似于 iOS 導(dǎo)航欄效果的選項(xiàng),需要修改源碼。
react-navigation 目錄下 找到 Header.js-> _renderTitle()

  _renderTitle(props, options) {
    const style = {};
    const { transitionPreset } = this.props;

    if (Platform.OS === 'android') {
      // if (!options.hasLeftComponent) {
      //   style.left = 0;
      // }
      // if (!options.hasRightComponent) {
      //   style.right = 0;
      // }
        if ( !options.hasLeftComponent &&
            !options.hasRightComponent
        ) {
            style.left = 0;
            style.right = 0;
        }
        style.justifyContent = 'center';
    } else if (
      Platform.OS === 'ios' &&
      !options.hasLeftComponent &&
      !options.hasRightComponent
    ) {
      style.left = 0;
      style.right = 0;
    }

    return this._renderSubView(
      { ...props, style },
      'title',
      this._renderTitleComponent,
      transitionPreset === 'uikit'
        ? this.props.titleFromLeftInterpolator
        : this.props.titleInterpolator
    );
  }

若要修改返回按鈕圖標(biāo),替換 back-iconxxx.android.png

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容