Development environment setup

1. Software to be installed [Click the corresponding link to download it]

Windows / Mac

Environment depends on

  • Nodejs [LTS version recommended]

Coding tool/editor

  • Webstorm [need to break the decoder, taobao spend a few dollars to buy a bar]
  • vscode

Small program side tools

  • Wechat small program [recommended to install a stable version]
  • Headline applet
  • Baidu applet
  • Alipay small program
  • QQ small programs
  • Fast application
  • If you’re done downloading, you’ll see the screenshot below

2. Development environment configuration

  • After node is successfully installed
  • Open Terminal to check the node version
  • Node -v, the related information of v xx.xx.x is displayed, indicating that the installation is successful
  • Perform the following steps on the terminal
NPM install @tarojs/cli -g # 👽 taro v X.X.XCopy the code

3. Simple Hello World project experience

  • Project is the name of your generated project, whatever you want to call it. Examples include Example, test, demo, etc
  • Then press Enter and go to the default for the first time
# taro init project CD # taro init project CD # taro init project CDCopy the code

-[note] : If you get an error with NPM install, don’t panic.

rm -rf node_modules package-lock.json
npm install
Copy the code

Figure 1: Figure 2:

4. Introduction to generate project directory

.

├─ ├─ dev.js # ├─ ├.js # ├.js # ├─ dev.js # ├─ ├─ package.json # The core of the project. It contains information such as name, description, and version, as well as information needed to run, develop, and selectively publish projects to NPM. ├─ dist # ├─ project.config.json # ├─ SRC # source directory │ ├─ app.config.js # ├─ app ├─ ├─ ├─ ├.js # ├.js # ├─ ├.less # page CSS │ └ ─ ─ index. The JSX # page components, if it is a Vue program, this file as the index. The VueCopy the code

.

5. Start the local development environment

  • Note: NPM Run Dev: H5 / repealed P/TT are all local development hot updates.
  • Open terminal, CD to your project directory, and execute the following commands respectively.
  • Using the WebStorm editor, you can start in a different way. Such as

  • Using the vscode editor, click the upper right menu [Terminal] — [New Terminal] — to open a Terminal panel under the current project path. To start the corresponding service, run the following command:

H5

cd your project
npm run dev:h5
Copy the code
  • As shown in the following figure, the service is successfully started. After the service is successfully started, the listening site http://0.0.0.0:10089 is automatically opened in the browser

  • The renderings are as follows:

Appellate P

npm run dev:weapp
Copy the code
  • After executing the above command, the code will be converted to runnable code on the small program side in the dist directory

The following figure indicates that the service has been started successfully

  • The generated file directories are as follows:
  • Open the downloaded wechat development tool
  • Click the small program — “Import project –” directory [open the path of the project, go to Dist /] — “AppID if it has your own real value, no default –” finally click import and it will open. Such as

  • The renderings are as follows:

Tt Toutiao applet/Tiktok applet

npm run dev:tt
Copy the code
  • After executing the above command, the code will be converted to runnable code on the small program side in the dist directory

The following figure indicates that the service has been started successfully

  • The generated file directories are as follows
    • Open the downloaded Bytedance development tool
  • Click the small program — “Import –” [Open the project directory and go to Dist /]

  • The renderings are as follows:

Baidu Baidu small program

npm run dev:swan
Copy the code
  • After executing the above command, the code will be converted to runnable code on the small program side in the dist directory

The following figure indicates that the service has been started successfully

  • The generated file directories are as follows
    • Open the downloaded Baidu development tools
  • Click the small program — “plus âž• –” to import the project — “[Open the project directory, go to Dist /] –” No AppID, click the test number

Such as

  • The renderings are as follows:

Note that if you do not know what command to start the applet on the corresponding side, it is as follows:

NPM run dev:swan # NPM run dev:alipy # alipay NPM run dev:qq # QQ NPM run NPM run dev:h5 # h5 NPM run dev: quickApp #Copy the code

First acquaintance, write Taro

First, simple text rendering

import React, { Component } from 'react'
import { View, Text } from '@tarojs/components'

export default class Index extends Component {
  constructor() {
    super(a);this.state = {
      defaultValue: 'Hello World!! '
    };
  }

  componentWillMount() {}

  componentDidMount() {}

  componentWillUnmount() {}

  componentDidShow() {}

  componentDidHide() {}

  render() {
    const { defaultValue } = this.state

    return (
      <View className='home'>{/* Text rendering */}<Text style={{ color: 'red' }}>{defaultValue}</Text>
      </View>); }}// You can see the Hello Worl text display in the corresponding service. Just like the "Hello World" in the display effect I introduced above
// If you are curious, you may have noticed that our variable is wrapped with {}, yes. React's JSX syntax allows you to do event binding, express variables, implement simple JS logic, etc., i.e. write HTML in JS.
// ** All variables and simple JS logic need to be wrapped with {} ** Here is the key.

Copy the code

JSX arrays can only use array.map

import React, { Component } from 'react'
import { View, Text } from '@tarojs/components'

const testData = [
  {
    label: 'Monday'.id: 1.value: 'Monday'}, {label: 'Tuesday'.id: 2.value: 'Tuesday'}, {label: 'Wednesday'.id: 3.value: 'Wednesday',},];export default class Index extends Component {
  constructor() {
    super(a); }componentWillMount() {}

  componentDidMount() {}

  componentWillUnmount() {}

  componentDidShow() {}

  componentDidHide() {}

  render() {
    return (
      <View className='home'>
        {testData.map((item) => {
          return (
            <View key={item.id} className='home__week'>
              <Text>{item.label}</Text>
              <Text>{item.value}</Text>
            </View>
          );
        })}
      </View>); }}// The label and value values of each object of the testData array variable are displayed

Copy the code

Bind click events

import React, { Component } from 'react'
import { View, Text } from '@tarojs/components'



export default class Index extends Component {
  constructor() {
    super(a);this.state = {
      defaultValue: 'Hello World!! '.number: 0,}}componentWillMount() {}

  componentDidMount() {}

  componentWillUnmount() {}

  componentDidShow() {}

  componentDidHide() {}

  handleClick1 = () = > {
    this.setState({
      defaultValue: "1, 2, 3, changed!!"});console.log("You clicked on me now.");
  };
  
  render() {
  	const { defaultValue, number } = this.state;
    return (
      <View className='home'>{/* Text rendering */}<Text style={{ color: "red}} ">{defaultValue}</Text>{/* Bind click event, write 1 */}<View className='home__btn'>
          <Text onClick={this.handleClick1} className='home__btn--txt'>Click I change defaultValue</Text>
        </View>OnClick ={()=>this.fetchData()} */}<View
          onClick={()= >This.setstate ((prevState) => {return {number: prevstate. number + 1,}; }); }} style={styles.viewStyle} ><Text style={styles.viewStyleFont}>{number}</Text>
        </View>
      </View>); }}// 1. There are two ways to bind click events, and then you can bind onClick on any element you want the event to behave on.

One is that we declare a variable, which is an action you use to bind styles to tag elements. You can use a root variable to host small variables, and then mount them on the tag you want to add styles to. Such as:
/ / < the Text style = {styles. ViewStyleFont} > {number} < / Text >. Text is the tag that you want to mount to. ViewStyleFont is the style variable to add.

const styles = {
  viewStyle: {
    background: 'pink'.color: '#fff'
  },
  viewStyleFont: {
    fontSize: '14px'}}Copy the code
// This is a common style solution: bind the tag to a class, and then find the corresponding class to write the corresponding style.
// If in doubt, remember that CSS is bound like 
      
// Because the HTML class attribute is a Javascript reserved word, we need to write className. Ha, ha, ha. // So className='home', I give a variable className in the root tag, // Any subsequent elements contained in the tag bound to this home are its descendants. So here we use the BEM naming convention. / / BEM naming conventions: https://juejin.cn/post/6844903672162304013 // __block is used to concatenate child elements. // The ampersand represents a reference to the parent selector home Less is a preprocessor extension language for CSS. Convenient for our rapid development. / / on less and & : https://www.jianshu.com/p/127b0974cfc3 / / know about less: https://less.bootcss.com/ .home { padding: 16Px; // This compiles the output to.home__week &__week { display: flex; justify-content: space-between; font-size: 16Px; } // & refers to the parent's bound class: home. This will compile the output to.home__btn, which is the same as our home__btn binding. &__btn { width: 163Px; height: 38Px; display: flex; align-items: center; justify-content: center; background: linear-gradient(135deg, rgba(242.20.12.1) 0%,rgba(242.39.12.1) 70%,rgba(242.77.12.1) 100%); border-radius: 26Px; &--txt { font-size: 14Px; color: rgba(255.255.255.1); }}}Copy the code
  • State [small white and beginners can ignore]
  • DefaultValue = ‘1, 2, 3’ because it does not re-render the component. If you have elsint checksum installed, it will not work.
  • React maintains a State update queue. Each call to setState pushes the currently modified State into the queue. At the end of the process, React merges the queue and executes the callback. React is not asynchronous in the real sense. Taro is.
  • State is used in three ways
The first kind ofthis.setState({ number: this.state.number + 1 }) // this.state.number 0  The second,this.setState({ number: this.state.number + 1 },() = > {
    console.log("callback: ".this.state.number); / / 2}); The third kind ofthis.setState(prevState= > {
  console.log("func: " + prevState.number); / / 1
      return {
        number: prevState.number + 1
      };
    },() = >{
      console.log('now '+ this.state.number) / / 2
 });

Copy the code

4. Parent-child component communication

  • Props pass value communication
  • Child components

import React, { Component } from 'react';
import { View, Text } from '@tarojs/components';

export default class Child extends Component {
  static defaultProps = {
    langName: ' '.enName: ' '.onNameEvent: () = >{}};constructor() {
    super(a); }componentWillMount() {}

  componentDidMount() {}

  componentWillUnmount() {}

  componentDidShow() {}

  componentDidHide() {}

  emitNameEvent = (langName) = > {
    this.props.onNameEvent(langName);
  };

  // Interface description
  render() {
    const { langName, enName } = this.props;

    return (
      <View style={styles.container}>
        <Text onClick={()= > this.emitNameEvent(langName)}>{langName}</Text>
        <Text>{enName}</Text>
      </View>); }}const styles = {
  container: {
    width: '100%'.display: 'flex'.justifyContent: 'space-between',}};Copy the code
  • The parent component
import React, { Component } from 'react'
import { View, Text } from '@tarojs/components'
import Child from './components/test';

const testData = [
  {
    label: 'Monday'.id: 1.value: 'Monday'}, {label: 'Tuesday'.id: 2.value: 'Tuesday'}, {label: 'Wednesday'.id: 3.value: 'Wednesday',},];export default class Index extends Component {
  constructor() {
    super(a); }componentWillMount() {}

  componentDidMount() {}

  componentWillUnmount() {}

  componentDidShow() {}

  componentDidHide() {}

  render() {
    return (
      <View className='home'>
        {testData.map((item) => {
          return (
            <View key={item.id} className='home__week'>
              <Child
                langName={item.label}
                enName={item.value}
                onNameEvent={(name)= >{console.log(' get child component name',name)}} /></View>
          );
        })}
      </View>); }}Copy the code

Iv. Introduction of life cycle

  • The React component life cycle refers to the life hook functions that a React component executes during mount, update, and destruction.
class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date(a)}; }componentWillMount() {}
 
  componentDidMount() {}

  componentWillUpdate(nextProps, nextState) {}
    
  componentWillReceiveProps(nextProps) {}  
  
  componentDidUpdate(prevProps, prevState) {}

  shouldComponentUpdate(nextProps, nextState) {}

  componentWillUnmount() {}
  
  render() {
    return (
    <View>
        <Text>Hello, world!</Text>
        <Text>The time now is {this. State. Date. ToLocaleTimeString ()}.</Text>
      </View>); }}Copy the code

The life cycles in the above components are described briefly

Initialization phase

  • Constructor, as the name implies, the component’s constructor. This is where states are initialized, events are bound, and so on

Mount the stage

  • ComponentWillMount, called before the component is mounted to the DOM. A function that is executed before a component is mounted, usually following the constructor function
  • ComponentDidMount is executed when the component is mounted on a DOM node. The whole process is performed only once, usually in some asynchronous data pull and other actions

Update the stage

  • ShouldComponentUpdate (); shouldComponentUpdate (); shouldComponentUpdate (); shouldComponentUpdate (); Return true if the component’s state and props change, and the update of the current component begins. Reduces unnecessary rendering of components and optimizes component performance. Render optimization.

  • ComponentWillReceiveProps, incoming parameters (nextProps) as the parent component is passed to the child components of the new props, through the scope of this. To get their nextProps props and compare to conclude whether or not to call again render to render, It can effectively reduce the number of invalid renders and improve the development efficiency of cycles. Here you can perform some related operations, such as some function initialization, based on the new props

  • ComponentWillUpdate, a pre-render function used when a component is performing a Render update. [Rarely used]

  • PrevProps/prevState prevProps/prevState/componentDidUpdate (); prevProps/prevState (); prevProps/prevState The setState method is not allowed to change the state value during the update phase, otherwise it will cause the loop rerendering of render. [Rarely used]

Unloading phase

  • ComponentWillUnmount, executed when the component is ready to be destroyed. You can usually do some recycling here, such as a timer recycling operation such as -clearInterval (this.timer), and clearing manually created DOM elements in componentDidMount to avoid memory leaks.

5. Binding styles

  • Mode one: in line
{/* For text rendering, set text color */}
<Text style={{ color: 'red' }}>{defaultValue}</Text>
Copy the code
  • Method 2. Inline variable binding
  {/* Bind the click event, written as 2 */}
  <View style={styles.viewStyle}>
    <Text style={styles.viewStyleFont}>{number}</Text>
  </View>
        
 const styles = {
  viewStyle: {
    background: 'pink'.color: '#fff',},viewStyleFont: {
    fontSize: '14px',}};Copy the code
  • Bind class style class name
  • Style naming, following the BEM specification
 {/* Handwritten button */}
 <View className='home__btn'>
   <Text onClick={this.handleClick1} className='home__btn--txt'>Click I change Hello World</Text>
  </View>
Copy the code
.home {
  padding: 16Px;
  &__btn {
    width: 163Px;
    height: 38Px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(135deg, rgba(242.20.12.1) 0%,rgba(242.39.12.1) 70%,rgba(242.77.12.1) 100%);
    border-radius: 26Px;
    &--txt {
        font-size: 14Px;
        color: rgba(255.255.255.1); }}}Copy the code

An introduction to

  • This tutorial is suitable for developers who like to learn by doing or have no understanding of small program development.

Learn more

React and Vue frameworks learn from the actual use of the technology stack.

  • Taro Life Cycle
  • Encodes es6 syntax
  • The React framework
  • Vue framework
  • Official step-by-step learning documents
  • Flex layout

The advanced

  • The blog section
  • Taro making source

conclusion

  • Official Documents:
  • If you think my above installation even wordy, can directly see the official document installation and use
  • Summary of excellent learning resources