react 使用modx
作者:互联网
添加依赖
yarn add mobx mobx-react @babel/plugin-proposal-decorators
在 babel.config.js
添加配置
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
[
"@babel/plugin-proposal-decorators",
{
"legacy": true
}
]
]
};
配置全局modx
import {observable,action,makeObservable} from 'mobx';
class RootStore{
constructor() {
// 使用 makeObservable mobx6.0 才会更新视图
makeObservable(this);
}
@observable
name ="page";
@action
changeName(name){
this.name=name;
}
}
export default new RootStore();
根节点使用provide包裹
import { Provider } from 'mobx-react';
import React, { Component } from 'react';
import {View,Text} from 'react-native'
import Btn from './components/btn/Btn'
import RootStore from './mobx'
class App extends Component {
render() {
return (
<View>
<Provider RootStore={RootStore}>
<Btn></Btn>
</Provider>
</View>
);
}
}
export default App;
子节点使用
import React, { Component } from 'react';
import {View,Text} from 'react-native'
import {inject,observer} from 'mobx-react'
@inject("RootStore")
@observer
class Btn extends Component {
handelClick= ()=>{
this.props.RootStore.changeName('吴亦凡');
alert(JSON.stringify(this.props.RootStore.name));
}
render() {
return (
<View>
<Text onPress={this.handelClick}>btn:{this.props.RootStore.name}</Text>
</View>
);
}
}
export default Btn;
效果图
标签:name,modx,babel,react,mobx,使用,import,RootStore 来源: https://blog.csdn.net/qq_25438391/article/details/117883808