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 obj = {
username: "张三",
sex:"男"
}
@observable age = 18
@computed
get doubleAge() {
return this.age * 2
}
@action setName(name){
this.obj.username = name
}
@action setAge(){
console.log("this.age",this.age)
this.age+=this.age
}
}
const person = new Person()
export default person
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
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>
)
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33