基于Taro + Dva构建的适配不同端(微信小程序、H5、React-Native 等)的时装衣橱

本文主要是介绍基于Taro + Dva构建的适配不同端(微信小程序、H5、React-Native 等)的时装衣橱,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

前言

Taro 是一套遵循 React 语法规范的 多端开发 解决方案。现如今市面上端的形态多种多样,Web、React-Native、微信小程序等各种端大行其道,当业务要求同时在不同的端都要求有所表现的时候,针对不同的端去编写多套代码的成本显然非常高,这时候只编写一套代码就能够适配到多端的能力就显得极为需要。

使用 Taro,我们可以只书写一套代码,再通过 Taro 的编译工具,将源代码分别编译出可以在不同端(微信小程序、H5、React-Native 等)运行的代码。

该项目基于Taro,构建了一个时装衣橱的项目演示,涉及了一个电商平台完整的业务逻辑和功能点,如果这个项目能驾驭的了,相信大部分公司的其他React项目也就不在话下。

效果演示

查看demo请戳这里(请用chrome手机模式预览)

H5版 && 微信小程序版

image

image

技术栈

React + Taro + Dva

项目运行


git clone git@github.com:EasyTuan/taro-msparis.git# 国内镜像加速节点:git@gitee.com:easytuan/taro-msparis.gitcd taro-msparisnpm install# 开发时时监听编译小程序
npm run dev:weapp# 开发时时监听编译H5
npm run dev:h5# pages模版快速生成
npm run tep `文件名`

项目说明

git分支说明:

init:框架整体结构,不涉及任何业务逻辑

master:项目的稳定版本

feature:项目开发分支

目标功能

  • [x] 美衣列表 -- 完成
  • [x] 美衣详情 -- 完成
  • [x] 登录、注册 -- 完成
  • [x] 个人中心 -- 完成
  • [x] 优惠券 -- 完成
  • [x] 衣袋(购物车) -- 完成

业务介绍

目录结构

├── .temp                  // H5编译结果目录
├── .rn_temp               // RN编译结果目录
├── dist                   // 小程序编译结果目录
├── config                 // Taro配置目录
│   ├── dev.js                 // 开发时配置
│   ├── index.js               // 默认配置
│   └── prod.js                // 打包时配置
├── screenshots            // 项目截图,和项目开发无关
├── site                   // H5静态文件(打包文件)
├── src                    // 源码目录
│   ├── components             // 组件
│   ├── config                 // 项目开发配置
│   ├── images                 // 图片文件
│   ├── models                 // redux models
│   ├── pages                  // 页面文件目录
│   │   └── home
│   │       ├── index.js           // 页面逻辑
│   │       ├── index.scss         // 页面样式
│   │       ├── model.js           // 页面models
│   │       └── service.js        // 页面api
│   ├── styles             // 样式文件
│   ├── utils              // 常用工具类
│   ├── app.js             // 入口文件
│   └── index.html
├── package.json
└── template.js            // pages模版快速生成脚本,执行命令 npm run tep `文件名`

部分截图展示

首页 && 商品详情

image

 

image

衣袋 && 我的

image

 

image

登录 && 优惠券

image

 

image

taro的安装及使用

安装 Taro 开发工具 @tarojs/cli

使用 npm 或者 yarn 全局安装,或者直接使用npx

$ npm install -g @tarojs/cli
$ yarn global add @tarojs/cli

使用命令创建模板项目

$ taro init myApp

进入项目目录开始开发,可以选择小程序预览模式,或者 h5 预览模式,若使用微信小程序预览模式,则需要自行下载并打开微信开发者工具,选择预览项目根目录。

微信小程序编译预览模式

# npm script
$ npm run dev:weapp
# 仅限全局安装
$ taro build --type weapp --watch
# npx 用户也可以使用
$ npx taro build --type weapp --watch

H5 编译预览模式

# npm script
$ npm run dev:h5
# 仅限全局安装
$ taro build --type h5 --watch
# npx 用户也可以使用
$ npx taro build --type h5 --watch

RN 编译预览模式

# npm script
$ npm run dev:rn
# 仅限全局安装
$ taro build --type rn --watch
# npx 用户也可以使用
$ npx taro build --type rn --watch

当然到这一步有个大概的骨架,作为生产开发是不够的,这时候我们引入dva

$ npm i dva-core dva-loading --save

新建dva.js

import { create } from 'dva-core';
import { createLogger } from 'redux-logger';
import createLoading from 'dva-loading';let app;
let store;
let dispatch;function createApp(opt) {// redux日志// opt.onAction = [createLogger()];app = create(opt);app.use(createLoading({}));if (!global.registered) opt.models.forEach(model => app.model(model));global.registered = true;app.start();store = app._store;app.getStore = () => store;dispatch = store.dispatch;app.dispatch = dispatch;return app;
}export default {createApp,getDispatch() {return app.dispatch;}
}

并在入口文件导入

import dva from './utils/dva'
const dvaApp = dva.createApp({initialState: {},models: models,
});
const store = dvaApp.getStore();

dva集成好了,下面我们来封装下request网络请求吧

import Taro from '@tarojs/taro';
import { baseUrl, noConsole } from '../config';export default (options = { method: 'GET', data: {} }) => {if (!noConsole) {console.log(`${new Date().toLocaleString()}【 M=${options.url} 】P=${JSON.stringify(options.data)}`);}return Taro.request({url: baseUrl + options.url,data: options.data,headers: {'Content-Type': 'application/json',},method: options.method.toUpperCase(),}).then((res) => {const { statusCode, data } = res;if (statusCode >= 200 && statusCode < 300) {if (!noConsole) {console.log(`${new Date().toLocaleString()}【 M=${options.url} 】【接口响应:】`,res.data);}if (data.status !== 'ok') {Taro.showToast({title: `${res.data.error.message}~` || res.data.error.code,icon: 'none',mask: true,});}return data;} else {throw new Error(`网络请求错误,状态码${statusCode}`);}})
}

好了,是应该准备pages页面的开发了,本人比较喜欢umi的目录结构

  pages                  // 页面文件目录└── home├── index.js           // 页面逻辑├── index.scss         // 页面样式├── model.js           // 页面models└── service.css        // 页面api

一个page要生成4个文件?能否用脚本帮我们自动生成呢?那来写一个吧

 /*** pages模版快速生成脚本,执行命令 npm run tep `文件名`*/const fs = require('fs');const dirName = process.argv[2];if (!dirName) {console.log('文件夹名称不能为空!');console.log('示例:npm run tep test');process.exit(0);
}// 页面模版
const indexTep = `import Taro, { Component } from '@tarojs/taro';
import { View } from '@tarojs/components';
import { connect } from '@tarojs/redux';
import './index.scss';@connect(({${dirName}}) => ({...${dirName},
}))
export default class ${titleCase(dirName)} extends Component {config = {navigationBarTitleText: '${dirName}',};componentDidMount = () => {};render() {return (<View className="${dirName}-page">${dirName}</View>)}
}
`;// scss文件模版
const scssTep = `@import "../../styles/mixin";.${dirName}-page {@include wh(100%, 100%);
}
`;// model文件模版
const modelTep = `import * as ${dirName}Api from './service';export default {namespace: '${dirName}',state: {},effects: {* effectsDemo(_, { call, put }) {const { status, data } = yield call(${dirName}Api.demo, {});if (status === 'ok') {yield put({ type: 'save',payload: {topData: data,} });}},},reducers: {save(state, { payload }) {return { ...state, ...payload };},},};
`;// service页面模版
const serviceTep = `import Request from '../../utils/request';export const demo = (data) => {return Request({url: '路径',method: 'POST',data,});
};
`;fs.mkdirSync(`./src/pages/${dirName}`); // mkdir $1
process.chdir(`./src/pages/${dirName}`); // cd $1fs.writeFileSync('index.js', indexTep);
fs.writeFileSync('index.scss', scssTep);
fs.writeFileSync('model.js', modelTep);
fs.writeFileSync('service.js', serviceTep);console.log(`模版${dirName}已创建,请手动增加models`);function titleCase(str) {const array = str.toLowerCase().split(' ');for (let i = 0; i < array.length; i++) {array[i] = array[i][0].toUpperCase() + array[i].substring(1, array[i].length);}const string = array.join(' ');return string;
}process.exit(0);

现在是时候进行愉快的开发了。。。

目录结构

├── .temp                  // H5编译结果目录
├── .rn_temp               // RN编译结果目录
├── dist                   // 小程序编译结果目录
├── config                 // Taro配置目录
│   ├── dev.js                 // 开发时配置
│   ├── index.js               // 默认配置
│   └── prod.js                // 打包时配置
├── screenshots            // 项目截图,和项目开发无关
├── src                    // 源码目录
│   ├── components             // 组件
│   ├── config                 // 项目开发配置
│   ├── images                 // 图片文件
│   ├── models                 // redux models
│   ├── pages                  // 页面文件目录
│   │   └── home
│   │       ├── index.js           // 页面逻辑
│   │       ├── index.scss         // 页面样式
│   │       ├── model.js           // 页面models
│   │       └── service.js         // 页面api
│   ├── styles             // 样式文件
│   ├── utils              // 常用工具类
│   ├── app.js             // 入口文件
│   └── index.html
├── package.json
└── template.js            // pages模版快速生成脚本,执行命令 npm run tep `文件名`

写在最后

项目完整代码地址

文档

Taro开发文档

https://nervjs.github.io/taro/docs/README.html

dva开发文档地址

https://dvajs.com/

小程序开发文档

https://mp.weixin.qq.com/debug/wxadoc/dev/



作者:EasyTuan
链接:https://www.jianshu.com/p/72f1a730ace8
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

这篇关于基于Taro + Dva构建的适配不同端(微信小程序、H5、React-Native 等)的时装衣橱的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/509358

相关文章

问题:第一次世界大战的起止时间是 #其他#学习方法#微信

问题:第一次世界大战的起止时间是 A.1913 ~1918 年 B.1913 ~1918 年 C.1914 ~1918 年 D.1914 ~1919 年 参考答案如图所示

[职场] 护理专业简历怎么写 #经验分享#微信

护理专业简历怎么写   很多想成为一名护理方面的从业者,但是又不知道应该怎么制作一份简历,现在这里分享了一份护理方面的简历模板供大家参考。   蓝山山   年龄:24   号码:12345678910   地址:上海市 邮箱:jianli@jianli.com   教育背景   时间:2011-09到2015-06   学校:蓝山大学   专业:护理学   学历:本科

Spring Cloud:构建分布式系统的利器

引言 在当今的云计算和微服务架构时代,构建高效、可靠的分布式系统成为软件开发的重要任务。Spring Cloud 提供了一套完整的解决方案,帮助开发者快速构建分布式系统中的一些常见模式(例如配置管理、服务发现、断路器等)。本文将探讨 Spring Cloud 的定义、核心组件、应用场景以及未来的发展趋势。 什么是 Spring Cloud Spring Cloud 是一个基于 Spring

大学湖北中医药大学法医学试题及答案,分享几个实用搜题和学习工具 #微信#学习方法#职场发展

今天分享拥有拍照搜题、文字搜题、语音搜题、多重搜题等搜题模式,可以快速查找问题解析,加深对题目答案的理解。 1.快练题 这是一个网站 找题的网站海量题库,在线搜题,快速刷题~为您提供百万优质题库,直接搜索题库名称,支持多种刷题模式:顺序练习、语音听题、本地搜题、顺序阅读、模拟考试、组卷考试、赶快下载吧! 2.彩虹搜题 这是个老公众号了 支持手写输入,截图搜题,详细步骤,解题必备

uniapp接入微信小程序原生代码配置方案(优化版)

uniapp项目需要把微信小程序原生语法的功能代码嵌套过来,无需把原生代码转换为uniapp,可以配置拷贝的方式集成过来 1、拷贝代码包到src目录 2、vue.config.js中配置原生代码包直接拷贝到编译目录中 3、pages.json中配置分包目录,原生入口组件的路径 4、manifest.json中配置分包,使用原生组件 5、需要把原生代码包里的页面修改成组件的方

Java面试八股之怎么通过Java程序判断JVM是32位还是64位

怎么通过Java程序判断JVM是32位还是64位 可以通过Java程序内部检查系统属性来判断当前运行的JVM是32位还是64位。以下是一个简单的方法: public class JvmBitCheck {public static void main(String[] args) {String arch = System.getProperty("os.arch");String dataM

vue, 左右布局宽,可拖动改变

1:建立一个draggableMixin.js  混入的方式使用 2:代码如下draggableMixin.js  export default {data() {return {leftWidth: 330,isDragging: false,startX: 0,startWidth: 0,};},methods: {startDragging(e) {this.isDragging = tr

vue项目集成CanvasEditor实现Word在线编辑器

CanvasEditor实现Word在线编辑器 官网文档:https://hufe.club/canvas-editor-docs/guide/schema.html 源码地址:https://github.com/Hufe921/canvas-editor 前提声明: 由于CanvasEditor目前不支持vue、react 等框架开箱即用版,所以需要我们去Git下载源码,拿到其中两个主

React+TS前台项目实战(十七)-- 全局常用组件Dropdown封装

文章目录 前言Dropdown组件1. 功能分析2. 代码+详细注释3. 使用方式4. 效果展示 总结 前言 今天这篇主要讲全局Dropdown组件封装,可根据UI设计师要求自定义修改。 Dropdown组件 1. 功能分析 (1)通过position属性,可以控制下拉选项的位置 (2)通过传入width属性, 可以自定义下拉选项的宽度 (3)通过传入classN

js+css二级导航

效果 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Con