看了mobx的文档,想用mobx结合react.context封装一个计数器组件,
**目的
1.为了让mobx只在当前组件内部有作用域,同时也不希望在调用组件的时候额外设置props,就像用最普通的react组件那样使用
2.刚入坑mobx请大家看看这个demo的操作是否正确
(运行是正常的,就是探讨一下有没有改进的地方)
import PropType from "prop-types"
import {observable,computed,action,decorate} from "mobx"
import {observer} from "mobx-react";
//1.用decorate观察oState
class oState {
constructor(){
this.a=1
}
change(){
this.a=this.a+1
}
}
const mobxState=decorate(oState,{
a:observable,
change:action
})
//2.装饰父组件
const App=observer(class App extends React.Component {
render(){
return (
<div>
<button onClick={this.handleClick.bind(this)}>add</button>
{this.props.children}
</div>
)}
constructor(props){
super(props);
this.mobxState=new mobxState();//实例化被观察的mobxState
this.state={};
}
getChildContext(){
//将被观察的mobxState通过上下文传递
return {
mobxState:this.mobxState
}
}
handleClick(){
//父组件点击的时候让mobxState的a+1
this.mobxState.change()
}
})
//父组件例行公事,描述上下文的PropTypes
App.childContextTypes={
mobxState:PropType.object
}
//3.装饰子组件
const AppChild=observer(class AppChild extends React.Component {
render(){
return (
<div>
{
//让子组件显示a的值
this.context.mobxState.a
}
</div>
)}
})
//子组件例行公事,获取上下文
AppChild.contextTypes={
mobxState:PropType.object
}
//4.ReactDOM渲染结两个App组件互不影响,两个mobxState都有各自的局部作用域
const target=document.getElementById("box")
ReactDOM.render(
<div>
<App>
<AppChild></AppChild>
</App>
<App>
<AppChild></AppChild>
</App>
</div>
,target)