最近發(fā)現(xiàn)網(wǎng)上RN集成mobx各種花樣染厅,安裝各種過期插件玫芦,還都不對,我決定自己寫一個旨指,照著官網(wǎng)很簡單的集成好了。
轉(zhuǎn)載注明出處哦
安裝配置
- @babel/plugin-proposal-decorators // 是為了適配裝飾器格式
- mobx
- mobx-react
我這里的版本是
"@babel/plugin-proposal-decorators": "7.8.3",
"mobx": "5.15.4",
"mobx-react": "6.1.8",
根目錄下創(chuàng)建.babelrc
{
"presets": [
"module:metro-react-native-babel-preset"
],
"plugins": [
[
"@babel/plugin-proposal-decorators",
{
"legacy": true
}
]
]
}
集成
- 創(chuàng)建一個/多個store
import { observable, action } from 'mobx'
/**
* appstore為系統(tǒng)級store,用來處理app的常規(guī)數(shù)據(jù)
*/
// mobx 版本 < 6.0.0
class AppStore {
@observable num = '我是隨機數(shù)'
@observable count = 0
@action
setAppName(num: string) {
this.num = num
}
@action
addCount() {
this.count++
}
}
// mobx 版本>=6.0.0
class AppStore {
constructor() {
// 建議使用這種方式喳整,自動識別類型谆构,不需要再加前綴
makeAutoObservable(this)
}
num = '我是隨機數(shù)'
count = 0
setAppName(num: string) {
this.num = num
}
addCount() {
this.count++
}
}
export const appStore = new AppStore()
- 把多個store集中管理,便于初始化
import { appStore } from './store/app.store'
const mainStore = {
appStore
}
export default mainStore
- 初始化(在入口處框都,比如app.tsx搬素, index.js)
import * as React from 'react'
import { NavigationContainer } from '@react-navigation/native'
import TabScreen from './src/page/tabs/tab.screen'
import { Provider } from 'mobx-react'
import mainStore from './src/mobx/mainStore'
export default function App() {
return (
<Provider {...mainStore}>
<NavigationContainer>
<TabScreen />
</NavigationContainer>
</Provider>
)
}
- 使用
import React from 'react'
import { View, Text, Button } from 'react-native'
import { observer, inject } from 'mobx-react'
interface IP {
appStore?: any
navigation?: any
}
interface IS {}
@inject('appStore')
@observer
export default class HomeScreen extends React.Component<IP, IS> {
render() {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>Home!</Text>
<Text>{this.props.appStore.num}</Text>
<Button
title='去個人中心'
onPress={() => {
this.props.navigation.navigate('Profile')
}}
/>
<Button
title='隨機數(shù)'
onPress={() => this.props.appStore.setAppName(String(Math.random() * 100))}
/>
<Button
title={'點擊數(shù)' + this.props.appStore.count}
onPress={() => this.props.appStore.addCount()}
/>
</View>
)
}
}