创建react项目
npx create-react-app my-app
释放webpack配置
yarn eject(没有git提交需要commit一下,不要push)
下载装饰器插件
yarn add @babel/plugin-proposal-decorators
- 配置package.json
"babel": {
"plugins": [
[
"@babel/plugin-proposal-decorators",
{
"legacy": true
}
]
],
"presets": [
"react-app"
]
}
下载mbox和mbox-react
yarn add mbox mbox-react -D
新建store文件夹 store
store/person.js
import { observable,computed, action } from "mobx"
class Person {
// @observable 变量名 = 值
@observable obj = {
username: "张三",
sex:"男"
}
@observable age = 18
@computed //当age发生改变时, 自动触发
get doubleAge() {
return this.age * 2
}
@action setName(name){ // 用户操作 事件调用
this.obj.username = name
}
// @action 方法名(参数) {
// console.log(参数)
// }
@action setAge(){ // 用户操作 事件调用
console.log("this.age",this.age)
this.age+=this.age
}
}
const person = new Person()
export default person
store/index
import person from "./person.js"
const store = {
person
}
export default store
index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import store from './store'
import { Provider } from 'mobx-react'
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<Provider store={store}>
<App />
</Provider>
);
App.js
import React, { Component } from 'react'
import {inject,observer} from 'mobx-react'
@inject('store')
@observer
export default class App extends Component {
constructor(props) {
super(props)
this.state = {
age: 18
}
}
mutateAge = ()=>{
this.props.store.person.setAge()
}
componentDidMount() {
console.log("this.props",this.props)
}
render() {
return (
<div>
我是App组件
<ul>
<li>姓名:{this.props.store.person.obj.username}</li>
<li>年龄:{this.props.store.person.age}</li>
<li>双倍年龄:{this.props.store.person.doubleAge}</li>
<li>性别:{this.props.store.person.obj.sex}</li>
</ul>
<button onClick={this.mutateAge}>修改年龄</button>
</div>
)
}
}