1. 安装 mobx mobx-react
npm install mobx mobx-react --save
"mobx": "^6.3.3", "mobx-react": "^7.2.0"
2. 安装 @babel/plugin-proposal-decorators 装饰器
npm install @babel/plugin-proposal-decorators --save
"@babel/plugin-proposal-decorators": "^7.15.4"
3. 修改config-overrerides.js
const { override, addWebpackAlias, addDecoratorsLegacy} = require("customize-cra"); const path = require('path') module.exports = override( // 配置别名 addWebpackAlias({ ["@"]: path.resolve(__dirname, "src") }), // 配置装饰器 addDecoratorsLegacy() );
4. src下新建store文件夹,store文件夹下新建index.js 和 testStore.js
testStore.js
import {observable, action} from "mobx"; class testStore { @observable text = '测试mobx' // 定义变量 @action getFunction () {} // 定义函数 } export default new testStore();
store / index.js
import testStore from "./testStore"; const stores = { testStore } export default stores;
src / index.js
import {Provider} from "mobx-react"; import stores from "./store/index"; ReactDOM.render( <Provider {...stores}> <React.StrictMode> <BrowserRouter> <Suspense fallback={<div style={{width: '100vw', height: '100vh', background: '#000', color:'red'}}>loading</div>}> {renderRoutes(routes)} </Suspense> </BrowserRouter> </React.StrictMode> </Provider>, document.getElementById('root') );
在任意一个组件注入
import React, {Component} from "react"; import {inject, observer} from "mobx-react"; @inject('testStore') @observer class Demo extends Component { render () { const {text} = this.props.testStore return <div> <div>{text}</div> </div> } } export default Demo;