1、首先初始化react项目
create-react-app mobxdemo
2、下载mobx插件
yarn add mobx mobx-react --save
使用mobx需要先安装装饰器插件, 要不然项目会报错
下面是装饰器的安装和配置:
安装babel插件:
Babel >= 7.x
yarn add @babel/plugin-proposal-decorators --save
babel@6.x
yarn add babel-plugin-transform-decorators-legacy --save
修改package.json文件的babel配置项
Babel >= 7.x
{
"plugins": [
["@babel/plugin-proposal-decorators", { "legacy": true }],
]
}
babel@6.x
"babel": {
"plugins": [
"transform-decorators-legacy"
],
"presets": [
"react-app"
]
},
WX20190117-110142.png
原理这里就简单略过,只讲用法。
3、在项目中新建Mobx文件夹,里面新建一个appStore.js用于存储全局状态和修改的方法action
在最底层 index.js里面配置Provider
WX20190117-112612.png
代码:
//引入mobx插件
import {Provider} from 'mobx-react'
import AppStore from './Mobx/appStore'
ReactDOM.render(
<Provider store={AppStore}>
<App />
</Provider>
, document.getElementById('root'));
在appStore.js里面写入全局状态的state和需要用到的action
WX20190117-112621.png
代码:
//appStore.js
import {observable,action} from 'mobx';
var appStore = observable({
counter: 0
});
appStore.addCount = action(()=>{
appStore.counter+=1;
});
appStore.subCount = action(()=>{
if(appStore.counter<=0){
return;
}
appStore.counter-=1;
});
appStore.changeCount = action((key)=>{
if(key<=0){
appStore.counter=0;
}
appStore.counter=parseInt(key);
});
export default appStore
在需要用到的页面使用装饰器拿到全局状态的state
WX20190117-112648.png
代码:
//使用
import React, { Component } from 'react';
import {observer, inject} from 'mobx-react';
import './App.css';
//import appStore from './Mobx/appStore';
@inject('store')
@observer
class App extends Component {
constructor(props){
super(props);
this.state={
count:0
}
}
componentWillMount(){
const {store}=this.props
console.log(store)
}
addCount=()=>{
const {store}=this.props
store.addCount()
this.setState({
})
}
subCount=()=>{
const {store}=this.props
store.subCount()
}
changeText(e){
console.log(e.target.value)
appStore.changeCount(e.target.value)
}
render() {
let {store}=this.props
return (
<div className="App">
<button onClick={this.subCount}>-</button>
<input type="text" value={store.counter} onChange={(e)=>this.changeText(e)}/>
<button onClick={this.addCount}>+</button>
</div>
);
}
}
export default App;
网友评论