项目搭建
搭建全局脚手架
npm install -g create-react-app
在 cra 中使用非 eject 方式启用 decorator
初始化
npx create-react-app mobx-demo
安装改变 create-react-app 中 webpack 配置插件
yarn add -D react-app-rewired customize-cra @babel/plugin-proposal-decorators mobx mobx-react
在项⽬根⽬录创建 config-overrides.js 并写⼊以下内容:
const { override, addDecoratorsLegacy } = require("customize-cra")
module.exports = override(
addDecoratorsLegacy()
)
修改 package.json ⽂件中 scripts 脚本
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-app-rewired eject"
},
启动
yarn start
mbox使用步骤
初始化 mobx 容器仓库
index.js
import {observable, action, makeObservable} from 'mobx'
class Store·
constructor () {
makeObservable(this)
}
@observable count = 0
@action.bound increment () {
this.count ++
}
}
在组件中使用 mobx 容器状态
在组件是发起 action 修改容器状态
import {inject, observer, Provider} from 'mobx-react'
@inject('store')
@observer
class CountIndex extends React.Component {
constructor (props) {
super(props)
}
render () {
const { store } = this.props
return (
<div>
<p>{store.count}</p>
<button onClick={store.increment}>+</button>
</div>
)
}
}
使用 mobx-react 与 react 关联
<Provider store={new Store()}><CountIndex /></Provider>