一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第8天,点击查看活动详情。
前言
在前一天的更文中,我们已经完成了跨多端开发taro的基本基本框架搭建。今天我们整合一下taro-ui并总结一下遇到的坑。
集成taro-ui
作为taro伴生的ui组件库,我们在考虑适配和可迭代等时间业务的时候最好是使用taro-ui进行组件开发
安装taro-ui
如果你按照taro官网的步骤来,恭喜你,肯定会在整合完成之后遇到执行build命令无法打包的情况。因为我们现在taro的版本为3.x,直接执行官网提供的脚本命令npm install taro-ui下载的是2.x版本的ui库。无法兼容3.x。我直接说步骤吧
- 在package.json中的dependencies添加3.x版本的taro ui,添加完之后dependencies的内容如下
"dependencies": {
"@babel/runtime": "^7.7.7",
"@tarojs/components": "3.4.4",
"@tarojs/plugin-framework-react": "3.4.4",
"@tarojs/react": "3.4.4",
"@tarojs/runtime": "3.4.4",
"@tarojs/taro": "3.4.4",
"react": "^17.0.0",
"react-dom": "^17.0.0",
"taro-ui": "^3.0.0-alpha"
}
- 运行npm i进行下载 以下的步骤我们按照官网(taro-ui.jd.com/)来既可以了
- 配置需要额外编译的源码模块
引用官网的原话由于引用
node_modules的模块,默认不会编译,所以需要额外给 H5 配置esnextModules,我们在项目的config/index.js中新增如下配置项
h5: {
esnextModules: ['taro-ui']
}
最后config/index.js的代码如下
h5: {
publicPath: '/',
staticDirectory: 'static',
esnextModules: ['taro-ui'],
postcss: {
autoprefixer: {
enable: true,
config: {
}
},
cssModules: {
enable: false, // 默认为 false,如需使用 css modules 功能,则设为 true
config: {
namingPattern: 'module', // 转换模式,取值为 global/module
generateScopedName: '[name]__[local]___[hash:base64:5]'
}
}
}
}
使用taro-ui
在使用之前先说一个比较常见的问题,我们在引入的时候是全局引入还是按需引入?我在这里提出一点建议,能按需引入就按需引入,如果你的项目很小并且开发比较懒或者不太熟悉项目的话,可以使用全局引入
我举一个按需引入button的例子吧
- 引入css
按需引入官网是放在app.scss里了,我一开始考虑的是放在各个模块自己的index.scss中引入,但是考虑到如果多个组件都使用同一个组件的样式的话,可能@import会多次引用。这个地方我找个时间看卡该如何抉择吧,现在我放在了app.scs中了
对应的代码如下
@import "~taro-ui/dist/style/components/button.scss";
- 修改index.tsx文件 我们修改index.tsx中的代码如下
import { Component } from "react";
import { View, Text } from "@tarojs/components";
import { AtButton } from "taro-ui";
import "./index.scss";
export default class Index extends Component {
componentWillMount() {}
componentDidMount() {}
componentWillUnmount() {}
componentDidShow() {}
componentDidHide() {}
render() {
return (
<View className="index">
<Text>Hello world!</Text>
<AtButton type="primary" onClick={() => console.log("click~~")}>
按钮文案
</AtButton>
</View>
);
}
}
和一开的代码只有两处不同,我解释一下
import { AtButton } from "taro-ui";:代表从taro-ui中引入AtButton组件
<AtButton type="primary" onClick={() => console.log("click~~")}>按钮文案:定义按钮的type类型为primaey,点击之后打印click~~
最终的效果如下所示
结语
今天我们整合了taro-ui至我们的项目中,从明天开始我们就基于已有的京东购物小程序来进行需求分析,实现自己的电商小程序。最后说一下,大家如果有了自己的appid的话,可以现在改一下了,在project.config.jsonz中修改appid为自己的appid就可以了。
欢迎大家点赞留言多多交流!