React-Mobx项目demo实例

React-Mobx项目demo实例

         导语:本实例实现一个待办事项实例,实现mobX与React的结合。

1、项目文件构:

项目文件结构如下图:

2、核心文件内容:

  1、index.js:核心代码。

  2、jsconfig.json:使项目能够使用MobX的注解,内容如下:

{
  "compilerOptions": {
      "experimentalDecorators": true
  }
}

3、package.json:配置文件

{
  "name": "todos-mobx",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "custom-react-scripts": "0.2.1",
    "mobx": "^3.3.1",
    "mobx-react": "^4.3.4",
    "react": "^16.1.1",
    "react-dom": "^16.1.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },
  "devDependencies": {
    "mobx-react-devtools": "^4.2.15"
  }
}

3、项目类图:

业务逻辑如下:

 

3、index.js核心代码

import React, { Component } from "react";
import ReactDOM from "react-dom";
import { observer } from "mobx-react";
import { observable, computed, action } from "mobx"; 

//待办事项
class Todo {
  id = Math.random();
  @observable title =  "";
  @observable finished = false ;
  constructor(title){
    this.title = title;
  }
}

//所有的待办事项数量
class TodoList{
  @observable todos = [];
  @computed
  get unfinishedTodoCount(){
      return this.todos.filter(todo => !todo.finished).length;
  }
}

@observer
class TodoListView extends  Component{
  render(){
    return(
        <div>
            <ul>
                {this.props.todoList.todos.map(todo => (
                    <TodoView todo = {todo} key={todo.id}/>
                ))}
            </ul>
            剩余任务:{this.props.todoList.unfinishedTodoCount}
        </div>
    );
  }
}

const TodoView = observer(({todo}) =>{
  const  handleClick = action(() => (todo.finished = !todo.finished));
  return(
      <li>
        <input type="checkbox" checked={todo.finished} onClick={handleClick}/>
          {todo.title}
      </li>
  );
});

const  store = new TodoList();
store.todos.push(new Todo("第一个待办事项"));
store.todos.push(new Todo("第二个待变事项"));

ReactDOM.render(
  <TodoListView todoList={store}/>,
  document.getElementById("root")
);



猜你喜欢

转载自blog.csdn.net/hnust_yangjieyu/article/details/82972744