定义变量

  1. @observable price = 0;
  2. @observable amount = 1;

image.png

  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3. import {observable,action,makeAutoObservable} from 'mobx'
  4. import {observer}from 'mobx-react'
  5. //1.初始化mobx仓库
  6. class Store {
  7. @observable count = 0
  8. //一定要加这一行
  9. constructor(){
  10. makeAutoObservable(this)
  11. }
  12. @action
  13. increment=()=>{
  14. this.count++
  15. }
  16. }
  17. @observer
  18. class App extends React.Component{
  19. render(){
  20. const {store}=this.props
  21. return(
  22. <div>
  23. <h1>我是一个仓库</h1>
  24. <h2>{store.count}</h2>
  25. <button onClick={store.increment}>增加</button>
  26. </div>
  27. )
  28. }
  29. }
  30. ReactDOM.render(
  31. <App store={new Store()}/>,
  32. document.getElementById('root')
  33. );