- 下载相关包
npm install mobx mobx-react --save
npm install -D
@babel/plugin-proposal-decorators @babel/plugin-proposal-class-properties
@babel/plugin-proposal-private-methods @babel/plugin-proposal-private-property-in-object
- 配置babel文件(.babelrc)
"plugins": [
...
["@babel/plugin-proposal-decorators", { "legacy": true }],
["@babel/plugin-proposal-class-properties", { "loose": true }],
["@babel/plugin-proposal-private-methods", { "loose": true }],
["@babel/plugin-proposal-private-property-in-object", { "loose": true }],
...
]
// 如果是ts项目,需要在tsconfig.json中加入这一句话
{
"compilerOptions": {
...
"experimentalDecorators": true,
...
}
}
- 新建store文件夹,并创建index.tsx主文件以及相关store类,相关代码如下
● index.tsx
import ListStore from './ListStore';
const stores = {
ListStore,
};
export { stores };
export default stores;
● 新建一个ListStore测试类
import { action, makeObservable, observable, computed } from 'mobx';
class ListStore {
@observable count: number = 0;
@observable selectUserList: Array<{ name: string; key: string }> = [];
@action.bound
add() {
this.count += 1;
}
@action.bound
sub() {
this.count -= 1;
}
@computed
get countComputedVal() {
return this.count * 2;
}
@action.bound
handleSelectUserList(userList: Array<{ name: string; key: string }>) {
this.selectUserList = userList;
}
constructor() {
makeObservable(this);
}
}
export default new ListStore();
- 导入index.tsx主入文件中,并配置
import React from 'react';
import { createRoot } from 'react-dom/client';
import { Provider } from 'mobx-react';
import { ConfigProvider } from 'antd';
import zhCN from 'antd/lib/locale/zh_CN';
import moment from 'moment';
import App from './app';
import 'moment/locale/zh-cn';
moment.locale('en');
import stores from '@/store';
import 'antd/dist/antd.less';
import './global.less';
const root = createRoot(document.getElementById('root'));
root.render(
<Provider {...stores}>
<ConfigProvider
locale={zhCN}
getPopupContainer={(node) => document.body}
>
<App />
</ConfigProvider>
</Provider>,
);
5. 在页面中使用mobx中的状态,代码如下:
import { inject, observer } from 'mobx-react';
import React from 'react';
import { Button } from 'antd';
function Home(props) {
const { ListStore } = props;
const { count, add, sub, selectUserList } = ListStore;
return (
<div className="btn-div">
<div>数值:{count}</div>
<Button onClick={add}>+</Button>
<Button onClick={sub}>-</Button>
<div>
已选择的人员:{selectUserList.length > 0 ? selectUserList.map((v) => v.name).join('、') : '暂无选中人员'}
</div>
</div>
);
}
export default inject('ListStore')(observer(Home));