mobx-react 를 이용해 리액트 컴포넌트에 상태를 주입하는 방법


1. 함수형 컴포넌트

import React from 'react'
import { observer, inject } from 'mobx-react'

function Counter(props) {
  const { counter } = props
  return (
    <div>
      <h1>{counter.number}</h1>
      <button onClick={counter.increase}>+1</button>
      <button onClick={counter.decrease}>-1</button>
    </div>
  )
}

export default inject('counter')(observer(Counter))
// export default observer(inject("counter")(Counter)); // not works


2. 클래스 컴포넌트

import React, { Component } from 'react'
import { observer, inject } from 'mobx-react'

@inject('counter')
@observer
class Counter extends Component {
  render() {
    const { counter } = this.props
    return (
      <div>
        <h1>{counter.number}</h1>
        <button onClick={counter.increase}>+1</button>
        <button onClick={counter.decrease}>-1</button>
      </div>
    )
  }
}

export default Counter