Learn Taro from React+Ts

Documentation is based on Function+hooks

The first chapter hooks

Resolve stateless components where there is no state, lifecycle, this reference

1.1 useState

It’s used to declare state variables. The useState function takes our initial state and returns an array in which item [0] is the current state value and item [1] is a method function that can change the state value.

 import {useState} from 'react'
 function App() {
    const [count,setCount]=useState(0)
    const  changeCount= () = > {
      setCount(count+1)}return (
     <div>
        <h1>Counter: {count}</h1>
        <button onClick={changeCount}> change</button>
     </div>)}export default App
Copy the code

1.2 useEffect

UseEffect is pretty much componentDidMount, componentDidUpdate and componentWillUnmount

Grammar:

 useEffect(() = > { 
     // You can do anything with side effects here
     return () = > { // Execute before component uninstallation
         // Do some finishing touches here, such as clearing timers/unsubscribing etc
     }
 }, [count]) // Use the second argument to tell React to execute the side effect function we passed (the first argument) only if the value of this argument changes. If it is [], the callback will only be executed after the first render()
Copy the code
 import {useState,useEffect} from 'react'
 function App() {
    const [count,setCount]=useState(0)
    const  changeCount= () = > {
      setTimeout(() = > {
        setCount(count+1)},1000)

    }
   useEffect(() = > {
     changeCount()
   })
    return (
     <div>
        <h1>Counter: {count}</h1>
        <button onClick={changeCount}> change</button>
     </div>)}export default App

Copy the code

React Basic syntax

2.1. Initialize the project

NPM install create-g react-app create-g react-app create-g react-app create-g react-app create-g react-app create-g react-app create-g react-app Hello-react is the project name CD hello-react // Switch to the project directory NPM startCopy the code

2.2. Understanding and use of JSX

The react virtual DOM(element) object is created as an XML+JS extension

function App() {
  return (
    <div className="App">
      <h1>hello world!</h1>
    </div>
  );
}
export default App;
Copy the code

2.2.1 Variable Binding

Variable binding with {}

 import {useState} from 'react'
 function App() {
    const [msg,setCount]=useState("hello")
    return (
     <div>
        <h1>{msg}</h1>
     </div>)}export default App
Copy the code

Use multiple Usestates, not limited to primitive types, but also objects and arrays

 const [count,setCount]=useState(0)
 const [flag,setFlag]=useState(true)
Copy the code

2.2.2 Conditional rendering

The &&(or) operator is used to achieve the same effect as v-if.

 import {useState} from 'react'
 function App() {
    const [flag,setFlag]=useState(true)
    return (
     <div>
       {flag && <h1>hello</h1>}
     </div>)}export default App
Copy the code

2.2.3 List rendering

Map traverses label inserts to add keys to bound elements

 import {useState} from 'react'
 function App() {
    const [tempList,setFlag]=useState([{name:"foo".age:18}, {name:"bar".age:20}, {name:"jack".age:22}])
    return (
     <div>
       <ul>
         {
           tempList.map((item,index) => {
             return <li key={index}>{item.name}---{item.age}</li>})}</ul>
     </div>)}export default App

Copy the code

2.2.4 Event Binding

Bind the event via onClick, but the class component does not have this. It is recommended to use the arrow function to bind this

 import {useState} from 'react'
 function App() {
    const [msg,setMsg]=useState("hello")
    // const [count,setCount]=useState({name:"foo"})
    const changeMsg= () = > {
      setMsg("world")}return (
     <div>
         <h1>{msg}</h1>
         <button onClick={changeMsg}>changeMsg</button>
     </div>)}export default App
Copy the code

Chapter 3. React componentized development

3.1. Basic understanding and use

function MyComponent1() {
   return (<h1>The factory function</h1>)}Copy the code

3.2. props

The parent component uploads values to the child component label

 import {useState} from 'react'
 import Children from "./components/Children/Children";
 function App() {
    const [msg,setMsg]=useState("hello")
    return (
     <div>
         <Children text={msg}/>
     </div>)}export default App
Copy the code

Subcomponents receive via props

function Children(props) {
  return (
      <div>I am the value passed by the parent component {props. Text}</div>)}export  default Children
Copy the code

3.3. refs

Function: find the real DOM element object inside the component, then operate it in three ways: method 1: ref="input1"  // It is a string of charactersRef ={input= > this.input1 = input}// callback function formMyRef = react.createref ()// Create a ref container formMethod 4:Copy the code

Example code: Method one

class UserInput extends React.Component {
        handlerClick = () = > {
          // Get the DOM from ref
          let { input1 } = this.refs;
          alert(input1.value);
        };
        render() {
          return (
            <div>// Method 1:<input type="text" ref="input1" />
              &nbsp;
              <button onClick={this.handlerClick}>Pop-up data</button>&nbsp;
            </div>
          );
        }
      }
ReactDOM.render(<UserInput />.document.getElementById("example")); 
Copy the code

Way 2

class UserInput extends React.Component {
        handlerClick = () = > {
          // Get the DOM from ref
          alert(this.input1.value);
        };
        render() {
          return (
            <div>{/* Mode two inptu parameter, custom, inptut1 method name */}<input type="text" ref={(input)= > (this.input1 = input)} />
              <button onClick={this.handlerClick}>Pop-up data</button>&nbsp;
            </div>
          );
        }
      }
ReactDOM.render(<UserInput />.document.getElementById("example"));
Copy the code

Methods three

 class UserInput extends React.Component {
        // Create a ref container
        // This container is a "special container" that can hold only one element
        myRef = React.createRef();
        handlerClick = () = > {
          // To get the DOM from ref, we need to get the value from the current attribute
          let { current } = this.myRef;
          alert(current.value);
        };
        render() {
          return (
            <div>{/* Place the current element in the myRef container on the component object */}<input type="text" ref={this.myRef} />
              <button onClick={this.handlerClick}>Pop-up data</button>&nbsp;
            </div>
          );
        }
      }
ReactDOM.render(<UserInput />.document.getElementById("example"));
Copy the code

The fourth chapter Taro

4.1 Installing taro and initializing the project

npm install -g @tarojs/cli	//step1 install taro globally
taro init taro-demo  		//step2 initialize taro
							//step3 configure a series of templates
npm run dev:weapp			//step4 run wechat applets
Copy the code

4.2 Use of basic Components

import { View, Text} from '@tarojs/components'
import './index.styl'

function Index() {
  return (
    <View>
      <Text>hello  world</Text>
    </View>
  )
}
export default Index
Copy the code

4.3 Life cycle function

//1. Use taro's own
import  {useDidShow} from "@tarojs/taro";
useDidShow (() = > {
    console.log('Page display callback')})//2. Use react hooks
import {useEffect} from 'react'
useEffect(() = > {
    console.log('Page load, update, unload callback')})Copy the code

4.4 Route Navigation

Taro.switchTab  // Jump to the tabBar page and close all other non-Tabbar pages
Taro.reLaunch	// Close all pages to open a page within the app
Taro.redirectTo	// Close the current page and go to a page in the application. However, jumping to the Tabbar page is not allowed.
Taro.navigateTo // Leave the current page and jump to a page in the application. But you cannot jump to the Tabbar page.
Taro.navigateBack // Close the current page and return to the previous page or multi-level page. You can use getCurrentPages to get the current page stack and determine how many layers you need to return.
EventChannel	// Triggers an event
Copy the code

4.4.1 Route Redirection

//1. Configure the page route in app.config.ts
pages: [
    'pages/demo/demo'].Copy the code
//2. Implement the jump in the component
Taro.navigateTo({
    url:"/pages/demo/demo".success(){
        console.log('Jump successful')}})Copy the code

4.4.2 Route Parameter Transmission

Taro.navigateTo({
    url:"/pages/demo/demo? id=2&age=18".success(){
        console.log('Jump successful')}})Copy the code
// Accept the parameters as passed
 const Param: any= getCurrentInstance()? .router? .params; useDidShow(() = > {
     console.log(Param)
 })
Copy the code

4.5 Event System

No parameters

function pageUrl() {
    console.log()} <Button onClick={pageUrl}> </Button>Copy the code

With the event

function pageUrl(e) {
    console.log(e)} <Button onClick={pageUrl}> </Button>Copy the code

Custom parameters

function pageUrl(a) {
    console.log(a)
}
<Button onClick={() = > { pageUrl('aaa'Button)}} > < / Button >Copy the code

4.6 commonly used API

useReachBottom		// Pull bottom loading
usePullDownRefresh	// Drop refresh

usePullDownRefresh(() = > {
    console.log('usePullDownRefresh')})Copy the code

4.6.1 Interface Interaction

Taro.showToast

Taro.showToast({
  title: 'success'.icon: 'success',})Copy the code

4.7 Network Request

IO /dist/#/doc/…

Url.ts Configures and exposes the URL

const demoUrl = '/app/perform/task';
export {
	demoUrl
}
Copy the code

Used in components

import {fly, demoUrl} from ".. /.. /.. /huanyou/url";
fly.post(demoUrl,params)
.then((res) = >{})
.catch((err) = >{})
Copy the code

The fifth chapter Taro – the UI

use

Taro 3 can only be used with taro-ui@next version

npm i taro-ui@next
Copy the code

Add the following configuration items to the config/index.js file of the taro project:

h5: {
  esnextModules: ['taro-ui']}Copy the code

Use in components

import { AtButton } from 'taro-ui'
import 'taro-ui/dist/style/index.scss'
render () {
    return (
      <View className='index'>
         <AtButton type='primary'>button</AtButton>
      </View>)}Copy the code

Icon

import "taro-ui/dist/style/components/icon.scss";

<View className="at-icon at-icon-chevron-right" />
Copy the code