preface
Because recently began to prepare for the graduation project, my graduation project is to do a small program, then began to learn how to develop small program journey.
Taro is an open cross-end cross-framework solution that supports the use of React/Vue/Nerv frameworks to develop wechat, JD.com, Baidu, Alipay, Bytedance, QQ mini program/H5 and other applications.
Therefore, using Taro, you only need to write one set of code to have the ability to adapt to multiple applications. Taro currently has 27.9k stars on Github, which is one of the reasons why I choose to learn Taro. (although the whole tutorial pit is actually a little bit more……)
Let’s get started.
Official documents: Taro official documents
An introduction to
Because I have some front-end development experience, SO I directly from the gradual introduction to the tutorial, through the hands-on step by step.
Progressive introduction tutorial
Progressive tutorial source code
The step-by-step introduction to developing a simple V2EX forum client using Taro is divided into four parts:
- Environment to prepare
- Basic tutorial
- Project progression and optimization
- The development of diverse
Here’s a look at some of the points not covered in the tutorial and some of the key ones.
Environment to prepare
Using Taro development requires installation:
Taro CLI
Node.js
Taro CLI Installation instructions:
npm i -g @tarojs/cli
Copy the code
After the installation is complete, enter taro on the terminal. If similar information is displayed, the installation is successful:
👽 Taro v3.0.0-beta.6 Usage: Taro <command> [options] options: -V, --version output the version number -h, --help output usage information Commands: init [projectName] Init a project with default templete config <cmd> Taro config create Create page for project build Build a project with options update Update packages of taro convert Convert weapp to taro info Diagnostics Taro env info doctor Diagnose taro project help [cmd] display help for [cmd]Copy the code
Basic tutorial
component
In applets, components are divided into page components and base components. Page components are those components that can be routed to a specified page and have a life cycle. Base components are common components that do not constitute a page but are part of a page or component.
Page components
Page components are typically defined in the Pages folder:
Taking the thread_detail component as an example, there are three files in this folder:
index.css
: style filethread_detail.tsx
Components:thread_detail.config.ts
: page component configuration file
Configuration files mainly configure some basic styles and text, page configuration, such as:
backgroundTextStyle: 'light',
navigationBarBackgroundColor: '#fff',
navigationBarTitleText: 'WeChat',
navigationBarTextStyle: 'black'
Copy the code
In thread_detail.config.ts it looks like this:
Export default {navigationBarTitleText: 'topic'}Copy the code
This configuration file must be written, otherwise the following error will be reported when the project is packaged:
Module not found: Can't resolve './pages/ XXX /xxx.config 'in' XXXX 'Copy the code
So let’s be careful here.
Types of components:
import React, { Component } from 'react'
import { View } from '@tarojs/components'
class Index extends Component {
// All React component methods can be used
componentDidMount () {}
// onLoad
onLoad () {}
// onReady
onReady () {}
/ / the corresponding onShow
componentDidShow () {}
/ / the corresponding onHide
componentDidHide () {}
/ / corresponding onPullDownRefresh, besides componentDidShow/componentDidHide,
// All page life cycle function names correspond to applets
onPullDownRefresh () {}
render () {
return (
<View className='index' />)}}export default Index
Copy the code
Function components:
import React, { useEffect } from 'react'
import { View } from '@tarojs/components'
import {
useReady,
useDidShow,
useDidHide,
usePullDownRefresh
} from '@tarojs/taro'
function Index () {
// All React Hooks can be used
useEffect(() = > {})
/ / the corresponding onReady
useReady(() = > {})
/ / the corresponding onShow
useDidShow(() = > {})
/ / the corresponding onHide
useDidHide(() = > {})
// Taro implements custom React Hooks for all applet page lifecyres
// For details, please refer to: [Taro Documentation] -> [Advanced Guidelines] -> Hooks]
usePullDownRefresh(() = > {})
return (
<View className='index' />)}export default Index
Copy the code
Based on the component
The base components are typically defined under the Components folder:
There is no need to set up configuration files for each component.
Entrance to the configuration
App.config. ts is the entry configuration file where you can configure the page path list, the global default window representation, and so on. Taro’s configuration specification is based on the global configuration of wechat applets: wechat applets global configuration.
In V2EX, the global configuration is as follows:
// app.config.ts
export default {
pages: [
'pages/index/index'.'pages/nodes/nodes'.'pages/hot/hot'.'pages/node_detail/node_detail'.'pages/thread_detail/thread_detail',].tabBar: {
list: [{
'iconPath': 'resource/latest.png'.'selectedIconPath': 'resource/lastest_on.png'.pagePath: 'pages/index/index'.text: 'new'
}, {
'iconPath': 'resource/hotest.png'.'selectedIconPath': 'resource/hotest_on.png'.pagePath: 'pages/hot/hot'.text: 'hot'
}, {
'iconPath': 'resource/node.png'.'selectedIconPath': 'resource/node_on.png'.pagePath: 'pages/nodes/nodes'.text: 'nodes'}].'color': '# 000'.'selectedColor': '#56abe4'.'backgroundColor': '#fff'.'borderStyle': 'white'
},
window: {
backgroundTextStyle: 'light'.navigationBarBackgroundColor: '#fff'.navigationBarTitleText: 'WeChat'.navigationBarTextStyle: 'black'}}Copy the code
routing
Routing hop
In Taro, you can use Taro’s navigateTo method to redirect routes:
Taro.navigateTo({ url: '/pages/thread_detail/thread_detail' })
Copy the code
This usage is similar to the function.history.push (‘/ XXX ‘) in React.
Routing parameters
In the page component, either getCurrentInstance().router or Current. Router? .params gets the routing parameters of the current page:
import Taro, { Current } from '@tarojs/taro';
// Inside the component
const{ full_name } = Current.router? .params;Copy the code
The life cycle
Both the React component lifecycle methods and the applet lifecycle methods are supported in Taro, but it is important to note when and in what order they are triggered. See the official documentation: Lifecycle triggering mechanisms.
Built-in component
Taro was developed using built-in components of the applet specification, such as
To use these built-in components in React, we must import them from @tarojs/ Components. The props of the component follow the big camel name convention:
// Small program writing
<view hover-class='test' />
Copy the code
/ / Taro
import { View } from '@tarojs/components'
<View hoverClass='test' />
Copy the code
The event
Events in Taro follow the camelCase naming convention, and all built-in event names start with ON.
In the event callback function, the first argument is the event itself, where stopPropagation is called to prevent bubbling.
function Comp () {
function clickHandler (e) {
e.stopPropagation() // Prevent bubbling
}
function scrollHandler () {}
// Only the applet bindtap corresponds to Taro's onClick
// Replace bind with ON to represent the name of the Taro event (with the exception of alipay applet, whose events start with ON)
return <ScrollView onClick={clickHandler} onScroll={scrollHandler} />
}
Copy the code
Project progression and optimization
After the project is developed, we want to see how the effect of the project is, how to do it? At that time, I was a little confused, so I turned to an official Taro Taro video for a 5-minute hands-on mini program and found the answer.
First, package and compile. Using the Taro CLI-generated project, package.json has been configured with instructions to package and compile various applets:
For example, IF I want to package the small wechat program, I will enter:
npm run dev:weapp
Copy the code
NPM run dev is executed for debugging, and NPM run Build is executed for package build to production.
If you want multiple compilations, modify the outputRoot property in index.js under config:
outputRoot: `dist/${process.env.TARO_ENV}`
Copy the code
In this way, files packaged on all ends can be stored in the dist folder at the same time. For example, the path of wechat mini-programs is dist/ appellate P, and that of H5 is dist/ H5.
Then, open the wechat developer tool, import the packaged and compiled project, there is the effect:
However, at this time, my project encountered a bug, and an error was reported in the wechat developer tool:
I didn’t read the error information carefully at that time. Actually, there was a prompt error position when I clicked in the second line Thread. Render. I thought: This can’t be debugged… There’s no console.log. (Actually, you can.)
So I thought, could it be packaged as H5 and debugged in the browser, so that it would be the same as front-end development? So he turned the other way. But in the browser, there will be a problem of cross-domain, localhost’s ask https://www.v2ex.com/api/ for a breach of the browser’s same origin policy. Applets are not limited by the same origin policy, so this problem does not occur.
Taro
H5 Cross domain problem solving
First, add the h5 configuration in config/dev.js:
h5: {
devServer: {
proxy: {
'/api/': {
target: "https://www.v2ex.com".changeOrigin: true
// pathRewrite: {
// '^/api/': '/'
// },}}}}Copy the code
The configuration is the devServer configuration for WebPack, see the blog: Proxy cross Domain for devServer
2. Modify HOST in api.ts:
const HOST_URI = 'https://www.v2ex.com/api/'
/ / changed to
const HOST_URI = '/api/'
Copy the code
Why did you change that? Because in proxy, we will check whether the request starts with/API /. If it starts with HTTP, we will check for a mismatch, do not go through proxy, and cross domain failure. The default domain name http://localhost:xxxx will be changed to target, which is the https://www.v2ex.com address. But under the browser F12, Network – > Headers or see http://localhost:xxxx/api/xxx, but the real request address is: https://www.v2ex.com/api/xxx.
The pathRewrite attribute needs to be added when you meet/API/and do the proxy, but there is no/API/in the real request, so you remove/API/from pathRewrite, so that both the identifier and the request interface can remove/API /.
Run NPM run dev:h5, you can view the result in the browser:
Finally, the problem was caused by writing the life cycle function componentWillMount as componentWillUnmount. I searched for a long time, so that I wanted to hammer myself to death.
React doesn’t recommend using componentWillMount anymore, so we should put data fetching in componentDidMount:
async componentDidMount() {
this.setState({
thread: this.props.thread
})
}
Copy the code
Add a layer of judgment to render:
/ / components
// Render after loading thread data to prevent property of undefined error
const attrLen = Object.keys(thread).length;
{attrLen ? <Thread
node={thread.node}
title={thread.title}
last_modified={thread.last_modified}
replies={thread.replies}
tid={thread.id}
member={thread.member}
not_navi={true}
/> : null}
Copy the code
In fact, wechat Developer tool also has a complete debugger, you can see console.log and other results, so we can directly modify the code in VSCode, after CTRL s, you can see the corresponding rendering results in wechat Developer tool, you can also debug by looking at the Console. However, wechat developer tools do not seem to be able to use Redux debugging tools, this will be studied later.
Refactoring this demo using hooks: taro-mini-Program.
Learning materials
Learn excellent resources: awesome- Taro