资讯专栏INFORMATION COLUMN

React+TypeScript+Mobx+AntDesignMobile进行移动端项目搭建

lindroid / 1430人阅读

摘要:通过装饰器或者利用时调用的函数来进行使用下面代码中当或者发生变化时,会监听数据变化确保通过触发方法自动更新。只能影响正在运行的函数,而无法影响当前函数调用的异步操作参考官方文档用法装饰器函数遵循中标准的绑定规则。

前言:

本文基于React+TypeScript+Mobx+AntDesignMobile技术栈,使用Create-React-App脚手架进行一个移动端项目搭建,主要介绍项目搭建过程和相关配置,以及状态管理工具Mobx的使用,最后实现点击按钮数字+1和一个简单的TodoList小功能,希望能对大家有所帮助。GitHub代码地址

项目搭建具体步骤:

安装Create-React-App脚手架工具,已经安装的同学请忽略

npm install create-react-app -g

创建初始项目
create-react-app my-app --typescript

注意:
如果同学你是参考typescript官方文档进行react项目搭建,里面有用create-react-app my-app --scripts-version=react-scripts-ts命令创建的,千万别用,现在已经过时了,
webpack版本有问题,后续配置各种想不到的坑 TypeScript中文官网

引入AntDesignMobile,实现组件按需加载

本步骤官网有比较详细的介绍,我就不一一列举配置过程了,建议大家不要eject暴露所有内建配置,后续版本升级维护可能比较麻烦,推荐使用 react-app-rewired 插件即可配置;AntDesignMobile官网

安装React路由,状态管理工具mobx,配置sass

    npm install history @types/history react-router-dom @types/react-router-dom // 安装react路由
    npm install mobx-react mobx  // 安装mobx
    npm install node-sass // 安装sass工具,安装之后无需另外配置sass,脚手架工具已经集成了
    

基本配置完成,运行项目
npm run start

React状态管理工具Mobx介绍:

Mobx是一个功能强大,基于面向对象编程方式的一个状态管理工具,上手相对比较容易。就连Redux的作者也曾经向大家推荐过它,对TypeScript支持比较友好,参考官网一张流程图:
Mobx中文官网

下面介绍几个Mobx核心概念
Observable state(可观察的状态)
MobX 为现有的数据结构(如对象,数组和类实例)添加了可观察的功能。 通过使用 @observable 装饰器(ES.Next)来给你的类属性添加注解就可以简单地完成这一切。
import { observable } from "mobx";
class Todo {
    id = Math.random();
    @observable title = "";
    @observable finished = false;
}
Computed values(计算值)
使用 MobX, 你可以定义在相关数据发生变化时自动更新的值。 通过@computed 装饰器或者利用 (extend)Observable 时调用 的getter / setter 函数来进行使用,下面代码中当queue或者refresh发生变化时,MobX会监听数据变化确保,通过Computed触发fooProps方法自动更新。
import React from "react";
import {observable, isArrayLike, computed, action, autorun, when, reaction,runInAction} from "mobx";
import {observer} from "mobx-react";

// 定义数据Store
class Store {
    @observable queue:number = 1;
    @action refresh = ():void => {
        this.queue += 1;
        console.log("this.queue -> ", this.queue);
    }
    @computed get fooProps():any {
        return {
            queue: this.queue,
            refresh: this.refresh
        };
    }
  }
Actions(动作)
任何应用都有动作。动作是任何用来修改状态的东西,mobx推荐将修改被观测变量的行为放在action中。action只能影响正在运行的函数,而无法影响当前函数调用的异步操作,参考官方文档用法:
action(fn)
action(name, fn)
@action classMethod() {}
@action(name) classMethod () {}
@action boundClassMethod = (args) => { body }
@action(name) boundClassMethod = (args) => { body }
@action.bound classMethod() {}
action 装饰器/函数遵循 javascript 中标准的绑定规则。 但是,action.bound 可以用来自动地将动作绑定到目标对象。 注意,与 action 不同的是,(@)action.bound 不需要一个name参数,名称将始终基于动作绑定的属性。
class Ticker {
    @observable tick = 0

    @action.bound
    increment() {
        this.tick++ // "this" 永远都是正确的
    }
}

const ticker = new Ticker()
setInterval(ticker.increment, 1000)
利用Mobx作为状态管理,实现两个小功能
点击按钮+1
import React from "react";
import {observable, isArrayLike, computed, action, autorun, when, reaction,runInAction} from "mobx";
import {observer} from "mobx-react";
import {Button} from "antd-mobile";
import "./index.scss";

// 定义数据Store,用Mobx作为状态管理工具
class Store {
    @observable queue:number = 1;
    @action refresh = ():void => {
        this.queue += 1;
        console.log("this.queue -> ", this.queue);
    }
    @computed get fooProps():any {
        return {
            queue: this.queue,
            refresh: this.refresh
        };
    }
  }
// ts组件接收父组件传递过来的数据必须定义接口类型,否则报错
interface BarProps{
    queue :number
}
// @observer修饰类,Bar组件接受Foo组建传过来的queue属性
@observer 
class Bar extends React.Component{
    render() {
        const {queue} = this.props
        return (
            
{queue}
) } } interface FooProps { queue: number, refresh():void } // Foo组件接收来自Add组件的store数据 @observer class Foo extends React.Component{ render() { const {queue,refresh} = this.props; return (
) } } // 初始化store数据,传递给Foo组件 const store = new Store(); class Add extends React.Component{ render() { return (

hello react-ts-mobx

) } } export default observer(Add)
TodoList功能
import React from "react";
import {observable, isArrayLike, computed, action, autorun, when, reaction,runInAction} from "mobx";
import {observer} from "mobx-react";
import "./index.scss";
// 定义Todo数据类型
class Todo {
    id:number = new Date().getTime();
    title:string = "";
    finished:boolean = false;
    constructor(title:string) {
        this.title = title;
    }
}
// Store数据方法管理
class Store {
    @observable title:string = "";
    @observable todos:Todo[] =[];
    // 添加Todo的Title
    @action createTitle (e:any) {
        console.log("e",e.target.value);
        this.title = e.target.value;
    }
    // 增加Todo数据
    @action createTodo = () => {
        this.todos.unshift(new Todo(this.title));
        this.title = "";
    }
    // 删除Todo
    @action delTodo (id:number) {
        this.todos.forEach((item,index) => {
            if (item.id === id) {
                this.todos.splice(index,1)
            }
        })
    }
    // 监听todos数据变化,显示剩余待办数量
    @computed get unfinished () {
        return this.todos.filter(todo => !todo.finished).length;
    }

}
interface TodoItemProps {
    todo:any;
    store:any;
}
// 每一条Todo数据组件
@observer 
class TodoItem extends React.Component {
    render() {
        const {todo,store} = this.props
        return (
            
{todo.title} store.delTodo(todo.id)}>X
) } } const store = new Store(); @observer class TodoList extends React.Component { render() { return (

TodoList

store.createTitle(e)} />
    {store.todos.map((todo)=>{ return
  • })}
{store.unfinished} item(s) unfinished
) } } export default TodoList
总结:

本人刚接触TypeScript和Mobx不久,总结学习方法:应该先熟悉一些基本概念后,慢慢的做一些小功能,遇到问题认真思考后再查资料或者请教别人,反复看文档,加强对知识的理解;欢迎大佬们留言交流;GitHub代码地址

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/105184.html

相关文章

  • React结合TypeScriptMobx初体验

    摘要:结合编辑器可以推导变量对应的类型以及内部的结构,提高代码的健壮性和可维护性。通过充分利用时间回溯的特征,可以增强业务的可预测性与错误定位能力。对于对象的哪部分需要成为可观察的,提供了细粒度的控制。 showImg(https://segmentfault.com/img/bVba6Ts?w=1218&h=525); 为什么要使用TypeScript 侦测错误 通过静态类型检测可以尽早检...

    dreambei 评论0 收藏0
  • 每周清单第 45 期: Safari 支持 Service Worker, Parcel 完整教

    摘要:的另一个核心特性,苹果表示也正在开发中,按开发进度可能几个月后就能与我们见面。是基于的本地化数据库,支持以及浏览器环境。 前端每周清单专注前端领域内容,以对外文资料的搜集为主,帮助开发者了解一周前端热点;分为新闻热点、开发教程、工程实践、深度阅读、开源项目、巅峰人生等栏目。欢迎关注【前端之巅】微信公众号(ID: frontshow),及时获取前端每周清单。 本期是 2017 年的最后一...

    赵春朋 评论0 收藏0
  • 2019年前的3个趋势

    摘要:组件成为前端最基本的物料,融合在组件中的方案日趋成熟。组件成为最基本的前端物料,让组件化更彻底在的调研报告中,开发者有愿意继续,有愿意继续。需要留意的是,有表示对感兴趣,因此获得的最感兴趣奖。 简介: JavaScript 应用范围广泛,静态类型语言 TypeScript 会继续得到更多开发者的青睐。 组件成为前端最基本的物料,CSS 融合在组件中(CSS in JS)的方案日趋成熟...

    yanwei 评论0 收藏0
  • 有个功能丰富的 react 脚手架,了解下?

    摘要:前言想要快速开始多页面应用项目结构如何更合理想要快速上手想要快速使用想要一键使用并能快速自定义主题样式可以的这里,受和的启发,我做了这样一个的脚手架,让你一键搭建项目,快速开始。 前言 想要快速开始 react 多页面应用? 项目结构如何更合理? 想要快速上手 Mobx? 想要快速使用 TypeScript? 想要一键使用 Ant-Design 并能快速自定义主题样式? 可以的!!! ...

    senntyou 评论0 收藏0
  • React全家桶环境搭建过程

    摘要:环境搭建从零开始搭建开发环境引入安装依赖新建修改引入并支持安装依赖打包时将样式模块化,我们可以通过或引入样式,并且相互不冲突。修改,引入创建使用语法报错修改引入状态管理使用装饰器语法修改修改源码 环境搭建 1.从零开始搭建webpack+react开发环境 2.引入Typescript 安装依赖 npm i -S @types/react @types/react-domnpm i -...

    Genng 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<