React-Mobx项目demo实例

本文提供了一个React结合MobX的待办事项应用demo,详细介绍了项目文件结构,包括index.js的核心代码,jsconfig.json配置,以及展示了项目类图,解释了业务逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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")
);



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值