typescript + react + mobx开发demo

发布者: xiaozhimn

第一步:安装react开发脚手架工具

npm install -gd create-react-app

第二步:创建一个typescript语法的react工程

create-react-app my-app --scripts-version=react-scripts-ts

第三步: 安装mobx

npm install mobx --save
npm install mobx-react --save
tsconfig.json中增加"experimentalDecorators": true //使用注解

第四步:在src目录下创建一个store.tsx文件

import { observable, action } from 'mobx';
class Store {
    @observable public title:string = '请点击我!';
    @action public changeTitle() {
        this.title = '已经点击了!';
    }
}
export default Store;

第五步:在App.tsx文件中引入

import './App.css';
import * as React from 'react';
import { observer } from 'mobx-react';
import logo from './logo.svg';
import Store from './store';
interface IAppProps {
  addTodo?: any;
  todos?: any;
}

const store = new Store();

@observer
class App extends React.Component<IAppProps> {
  public state = {
    count: 1
  }
  public constructor(props: any) {
    super(props);
  }
  public componentDidMount() {
    setInterval(()=> {
        this.state.count++;
        this.setState(this.state);
        store.title = "hello mobx";
    }, 500);
  }
  public render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title" onClick={store.changeTitle.bind(store)}>{store.title}</h1>
        </header>
        <p className="App-intro">
          To get started, edit <code>src/App.tsx</code> and save to reload.
        </p>
      </div>
    );
  }
}

export default App;

第六步: 查询运行结果

0赞