index
1import { render } from "react-dom";2import App from "./App";3import store from "./store";4import { Provider } from "mobx-react";56const rootElement = document.getElementById("root");7render(8 <Provider {...store}>9 <App />10 </Provider>,11 rootElement12);
store
1import { makeObservable, observable, action } from "mobx";23class Home {4 constructor() {5 makeObservable(this, {6 data: observable,7 onChange: action.bound8 });9 }10 data = "home";11 onChange(data) {12 this.data = data;13 }14}1516class About {17 constructor() {18 makeObservable(this, {19 value: observable,20 onChange: action.bound21 });22 }23 value = "About";24 onChange(value) {25 this.value = value;26 }27}28// 上⾯的模块应该分散在各⾃的业务中,这⾥就不使⽤导⼊的⽅式了29export default {30 home: new Home(),31 about: new About()32};
App
1import React from "react";2import { inject, Observer } from "mobx-react";34function MobxReact({ home, about }) {5 return (6 <h3>7 <h2>mobx-react</h2>8 <button onClick={() => home.onChange(Math.random())}>9 home:10 <Observer>{() => home.data}</Observer>11 </button>12 <br />13 <button onClick={() => about.onChange(Math.random())}>14 about:15 <Observer>{() => about.value}</Observer>16 </button>17 </h3>18 );19}2021export default inject("home", "about")(MobxReact);