### Batch Get Storage Example (for context) Source: https://github.com/nervjs/taro-docs/blob/master/docs/apis/storage/batchSetStorage.md This example shows how to retrieve data using batchGetStorage, which is related to batchSetStorage. It fetches data associated with a list of keys. ```typescript Taro.batchGetStorage({ keyList: ['key'] success(res) { console.log(res) } }) ``` -------------------------------- ### start Source: https://github.com/nervjs/taro-docs/blob/master/docs/apis/media/audio/MediaAudioPlayer.md Starts the audio player. This method is available in WeChat Mini Programs. ```APIDOC ## start ### Description Starts the audio player. ### Method (Implicitly a method call on a MediaAudioPlayer instance) ### Endpoint (Not applicable, SDK method) ### Parameters None ### Request Example ```tsx // Assuming player is an instance of MediaAudioPlayer player.start(); ``` ### Response #### Success Response - **Promise** - Resolves when playback starts. ``` -------------------------------- ### Install Harmony Plugin Source: https://github.com/nervjs/taro-docs/blob/master/blog/2025-05-16-taro-harmony-c-api.md Install the Taro Harmony C-API plugin using npm or pnpm. ```bash # 使用 npm 安装 $ npm i @tarojs/plugin-platform-harmony-cpp # 使用 pnpm 安装 $ pnpm i @tarojs/plugin-platform-harmony-cpp ``` -------------------------------- ### Install Redux and React-Redux Source: https://github.com/nervjs/taro-docs/blob/master/i18n/en/docusaurus-plugin-content-docs/current/guide.mdx Install the necessary packages for Redux integration. This is the first step to using Redux in your React application. ```bash npm i redux react-redux ``` -------------------------------- ### Choose Media Example Source: https://github.com/nervjs/taro-docs/blob/master/docs/apis/media/video/chooseMedia.md This example demonstrates how to use Taro.chooseMedia to select up to 9 images or videos from the album or camera. It also sets a maximum duration for video recording and specifies the camera to use. ```typescript Taro.chooseMedia({ count: 9, mediaType: ['image','video'], sourceType: ['album', 'camera'], maxDuration: 30, camera: 'back', success: (res) => { console.log(res.tempFiles) console.log(res.type) } }) ``` -------------------------------- ### start Source: https://github.com/nervjs/taro-docs/blob/master/docs/apis/media/recorder/RecorderManager.md Starts audio recording. This method is available on WeChat MiniProgram, Douyin MiniProgram, ASCF Yuan Service, and React Native. It accepts an options object to configure the recording. ```APIDOC ## start ### Description Starts audio recording. ### Method (option: StartOption) => void ### Parameters #### Request Body - **option** (StartOption) - Description for option ``` -------------------------------- ### Prerender Configuration Example Source: https://github.com/nervjs/taro-docs/blob/master/i18n/en/docusaurus-plugin-content-docs/current/prerender.md Configure prerender settings in your project's index.js, dev.js, or prod.js file. This example shows how to specify pages to include, exclude, and match for prerendering. ```javascript const config = { ... mini: { prerender: { match: 'pages/shop/**', // All pages starting with `pages/shop/` participate in prerender include: ['pages/any/way/index'], // `pages/any/way/index` will include prerender exclude: ['pages/shop/index/index'] // `pages/shop/index/index` will not prerender } } }; module.exports = config ``` -------------------------------- ### Install React Compatibility Component Library Source: https://github.com/nervjs/taro-docs/blob/master/i18n/en/docusaurus-plugin-content-docs/current/h5.md Install the React-based component library for better H5 compatibility. ```bash $ yarn add @tarojs/components-react ``` -------------------------------- ### View Component Examples (Vue) Source: https://github.com/nervjs/taro-docs/blob/master/i18n/en/docusaurus-plugin-content-docs/current/components/viewContainer/view.md Illustrates the use of the View component for layout with flexbox in a Vue environment. Includes template, script, and style sections for a complete example. ```html ``` -------------------------------- ### Install Vuex Source: https://github.com/nervjs/taro-docs/blob/master/i18n/en/docusaurus-plugin-content-docs/current/guide.mdx Install Vuex, the official state management library for Vue.js. This is required for managing application state in Vue components. ```bash npm i vuex ``` -------------------------------- ### Install Babel Runtime for Async Functions Source: https://github.com/nervjs/taro-docs/blob/master/blog/2020-01-08-taro-2-0.md Install necessary packages and configure Babel to enable async functions support in Taro 2.0. ```bash $ yarn add babel-plugin-transform-runtime --dev $ yarn add babel-runtime ``` -------------------------------- ### Manually Install Peer Dependencies Source: https://github.com/nervjs/taro-docs/blob/master/docs/react-native.md Manual installation steps for peer dependencies if `yarn upgradePeerdeps` fails. This involves directly using `install-peerdeps` and `pod-install`. ```shell install-peerdeps @tarojs/taro-rn -o -Y && install-peerdeps @tarojs/components-rn -o -Y && install-peerdeps @tarojs/router-rn -o -Y && pod-install ``` -------------------------------- ### Start Metro Server for Development Debugging Source: https://github.com/nervjs/taro-docs/blob/master/docs/react-native.md Starts the Metro server and prints a QR code for debugging with Taro Playground APP. Ensure the app is on the same network. ```shell yarn dev:rn --qr ``` -------------------------------- ### StartOption Source: https://github.com/nervjs/taro-docs/blob/master/i18n/en/docusaurus-plugin-content-docs/current/apis/media/live/LivePusherContext.md Options for the start method. ```APIDOC ## StartOption ### Description Options for the start method. ### Properties - **complete** (callback) - Optional - The callback function used when the API call completed (always executed whether the call succeeds or fails). - **fail** (callback) - Optional - The callback function for a failed API call. - **success** (callback) - Optional - The callback function for a successful API call. ``` -------------------------------- ### Send NFC Message Example Source: https://github.com/nervjs/taro-docs/blob/master/docs/apis/device/nfc/sendHCEMessage.md This example demonstrates how to send an NFC message using Taro.sendHCEMessage. It requires starting HCE first and listening for HCE messages. The message is sent when the message type is 1. ```typescript const buffer = new ArrayBuffer(1) const dataView = new DataView(buffer) dataView.setUint8(0, 0) Taro.startHCE({ success: function (res) { Taro.onHCEMessage(function (res) { if (res.messageType === 1) { Taro.sendHCEMessage({data: buffer}) } }) } }) ``` -------------------------------- ### startPreview Source: https://github.com/nervjs/taro-docs/blob/master/i18n/en/docusaurus-plugin-content-docs/current/apis/media/live/LivePusherContext.md Enables camera preview for live streaming. ```APIDOC ## startPreview ### Description Enables camera preview. ### Method (option?: StartPreviewOption) => void ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response None #### API Support | API | WeChat Mini-Program | H5 | React Native | | :---: | :---: | :---: | :---: | | LivePusherContext.startPreview | ✔️ | | | ``` -------------------------------- ### Vue3 Page Component Example Source: https://github.com/nervjs/taro-docs/blob/master/i18n/en/docusaurus-plugin-content-docs/current/vue-page.mdx Illustrates a Vue3 page component in Taro, showcasing the setup function and ref for reactive data. ```jsx ``` -------------------------------- ### startAdvertising Source: https://github.com/nervjs/taro-docs/blob/master/docs/apis/device/bluetooth-peripheral/BLEPeripheralServer.md Starts broadcasting the locally created peripheral device. This method is available on WeChat Mini Program and JD Mini Program. ```APIDOC ## startAdvertising ### Description Starts broadcasting the locally created peripheral device. ### Method ``` (option: Option) => Promise ``` ### Parameters #### Path Parameters - **option** (Option) - Required - The configuration object for starting advertising. ### Request Example ```json { "example": "// No request body example provided for this method." } ``` ### Response #### Success Response (200) - **TaroGeneral.BluetoothError** - An object indicating the result of the operation. #### Response Example ```json { "example": "// No response body example provided for this method." } ``` ``` -------------------------------- ### LivePusherContext.startPreview Source: https://github.com/nervjs/taro-docs/blob/master/docs/apis/media/live/LivePusherContext.md Starts the preview for live streaming. Accepts an options object for configuration. ```APIDOC ## LivePusherContext.startPreview ### Description Starts the preview for live streaming. This method can be configured using an options object. ### Parameters #### Request Body - **complete** (TaroGeneral.CallbackResult) - Optional - Callback function executed when the interface call ends (both success and failure). - **fail** (TaroGeneral.CallbackResult) - Optional - Callback function executed when the interface call fails. - **success** (TaroGeneral.CallbackResult) - Optional - Callback function executed when the interface call succeeds. ``` -------------------------------- ### Count Records in Collection Source: https://github.com/nervjs/taro-docs/blob/master/docs/apis/cloud/DB.md Use the `count` method to get the number of records matching a query. This example shows how to use it with a success callback. ```typescript const db = Taro.cloud.database() db.collection('todos').where({ _openid: 'xxx' // 填入当前用户 openid }).count().then(res => { console.log(res.total) }) ``` -------------------------------- ### Start Bundler in Existing 3.x Taro Project Source: https://github.com/nervjs/taro-docs/blob/master/blog/2020-12-02-taro-3-2-0-cannary-1.md To use the canary version in an existing 3.x project, update your `package.json` dependencies to `^3.2.0-canary.3` and reinstall. Then, start the bundler using the provided command. ```bash # Change the tarojs related dependency versions in `package.json` to `^3.2.0-canary.3` # Pay special attention to `@tarojs/taro-rn` and `@tarojs/rn-runner` which might be installed as 2.x versions # Reinstall dependencies $ yarn # Start the bundler $ yarn dev:rn --port 8081 # When the bundler starts successfully, the following information will be displayed # React-Native Dev server is running on port: 8081 ``` -------------------------------- ### Play Voice Source: https://github.com/nervjs/taro-docs/blob/master/docs/apis/media/audio/playVoice.md Starts playing a voice file. This example first records audio and then plays it back. The `filePath` is obtained from the `Taro.startRecord` success callback. ```typescript Taro.startRecord({ success: function (res) { const tempFilePath = res.tempFilePath Taro.playVoice({ filePath: tempFilePath, complete: function () { } }) } }) ``` -------------------------------- ### 调试 taro-init 命令配置 Source: https://github.com/nervjs/taro-docs/blob/master/docs/debug-config.md 配置 launch.json 以调试 'taro init projectName' 命令。指定目标目录和命令参数。 ```json { // ... "configurations": [ //... { // ... "cwd": "/Users/User/Desktop", "args": ["init", "projectName"] } ] } ``` -------------------------------- ### Add Plugin via webpackChain in H5 Source: https://github.com/nervjs/taro-docs/blob/master/docs/config-detail.md Customize Webpack configuration for H5 builds using webpackChain. This example demonstrates how to install and use a Webpack plugin. ```javascript // 这是一个添加插件的例子 module.exports = { // ... h5: { // ... webpackChain(chain, webpack) { chain.merge({ plugin: { install: { plugin: require('npm-install-webpack-plugin'), args: [ { // Use --save or --save-dev dev: false, // Install missing peerDependencies peerDependencies: true, // Reduce amount of console logging quiet: false, // npm command used inside company npm: 'cnpm', }, ], }, }, }) }, }, } ``` -------------------------------- ### onStart Source: https://github.com/nervjs/taro-docs/blob/master/docs/apis/media/recorder/RecorderManager.md Listens for the recording start event. This event is triggered when the recording process begins. ```APIDOC ## onStart ### Description Listens for the recording start event. ### Method (callback: (res: TaroGeneral.CallbackResult) => void) => void ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript RecorderManager.onStart(callback => { console.log('Recording started', callback) }) ``` ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### LivePusherContext.start Source: https://github.com/nervjs/taro-docs/blob/master/docs/apis/media/live/LivePusherContext.md Starts the live streaming process. Accepts an options object for configuration. ```APIDOC ## LivePusherContext.start ### Description Starts the live streaming process. This method can be configured using an options object. ### Parameters #### Request Body - **complete** (TaroGeneral.CallbackResult) - Optional - Callback function executed when the interface call ends (both success and failure). - **fail** (TaroGeneral.CallbackResult) - Optional - Callback function executed when the interface call fails. - **success** (TaroGeneral.CallbackResult) - Optional - Callback function executed when the interface call succeeds. ``` -------------------------------- ### Batch Get Storage Example Source: https://github.com/nervjs/taro-docs/blob/master/docs/apis/storage/batchGetStorage.md Demonstrates how to use Taro.batchGetStorage to retrieve data for a list of keys from local storage. The success callback logs the retrieved data. ```typescript Taro.batchGetStorage({ keyList: ['key'], success(res) { console.log(res) } }) ``` -------------------------------- ### start Source: https://github.com/nervjs/taro-docs/blob/master/docs/apis/ai/visionkit/VKSession.md Initiates the VK session. A callback is provided to receive status updates during the session startup process. ```APIDOC ## start ### Description Initiates the VK session. A callback is provided to receive status updates during the session startup process. ### Method Not applicable (JavaScript function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript VKSession.start(status => { console.log('Session status:', status); }); ``` ### Response #### Success Response This method does not return a value directly; it initiates the session and calls the provided callback with the status. #### Response Example None ``` -------------------------------- ### React Component Example Source: https://github.com/nervjs/taro-docs/blob/master/docs/README.mdx A basic React component demonstrating state management and rendering within a Taro application. Ensure React is installed and configured for your Taro project. ```jsx import React, { Component } from 'react' import { View, Text } from '@tarojs/components' export default class Index extends Component { state = { msg: 'Hello World!', } componentWillMount() {} componentDidShow() {} componentDidHide() {} render() { return ( {this.state.msg} ) } } ``` -------------------------------- ### Event Binding for Native Components in React Source: https://github.com/nervjs/taro-docs/blob/master/i18n/en/docusaurus-plugin-content-docs/current/hybrid.mdx Bind events to native components in React using hump case starting with 'on'. For example, 'onClick' corresponds to the native 'bind:click' event. ```jsx // Corresponding to bind:click Event Button // Corresponding to bind:after-read Event ``` -------------------------------- ### Configure Directory Aliases Source: https://github.com/nervjs/taro-docs/blob/master/docs/config-detail.md Set up directory aliases to simplify import paths. This example shows how to alias component and utility directories, as well as package files. ```javascript module.exports = { // ... alias: { '@/components': path.resolve(__dirname, '..', 'src/components'), '@/utils': path.resolve(__dirname, '..', 'src/utils'), '@/package': path.resolve(__dirname, '..', 'package.json'), '@/project': path.resolve(__dirname, '..', 'project.config.json'), }, } ``` -------------------------------- ### Get User Info with Credentials Source: https://github.com/nervjs/taro-docs/blob/master/i18n/en/docusaurus-plugin-content-docs/current/apis/open-api/user-info/getUserInfo.md This example shows how to call Taro.getUserInfo with `withCredentials` set to true, which requires a prior successful call to Taro.login and returns sensitive data like encryptedData and iv. ```javascript Taro.getUserInfo({ withCredentials: true, success: function (res) { console.log(res.userInfo); console.log(res.encryptedData); console.log(res.iv); }, fail: function (res) { console.log(res); } }); ``` -------------------------------- ### Get Saved File Info Source: https://github.com/nervjs/taro-docs/blob/master/docs/apis/files/getSavedFileInfo.md Use Taro.getSavedFileInfo to retrieve the size and creation time of a locally saved file. Ensure you provide a valid file path. This example demonstrates a successful callback. ```typescript Taro.getSavedFileInfo({ filePath: 'wxfile://somefile', //仅做示例用,非真正的文件路径 success: function (res) { console.log(res.size) console.log(res.createTime) } }) ``` -------------------------------- ### 调试 taro-build 命令配置 Source: https://github.com/nervjs/taro-docs/blob/master/docs/debug-config.md 配置 launch.json 以调试 'taro build --weapp --watch' 命令。指定目标项目的工作目录和命令参数。 ```json { // ... "configurations": [ //... { // ... "cwd": "/Users/User/Desktop/test", "args": ["build", "--type", "weapp", "--watch"] } ] } ``` -------------------------------- ### Choose Image Example Source: https://github.com/nervjs/taro-docs/blob/master/docs/apis/media/image/chooseImage.md This snippet demonstrates how to use Taro.chooseImage to select a single image from either the album or camera. It specifies image size types and handles the success callback to get the temporary file paths. ```typescript Taro.chooseImage({ count: 1, // 默认9 sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有 sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有,在H5浏览器端支持使用 `user` 和 `environment`分别指定为前后摄像头 success: function (res) { // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片 var tempFilePaths = res.tempFilePaths } }) ``` -------------------------------- ### Upload Task with Progress and Abort Source: https://github.com/nervjs/taro-docs/blob/master/docs/apis/network/upload/uploadFile.md This example shows how to use Taro.uploadFile to upload a file and get an UploadTask. The UploadTask can be used to monitor the upload progress via the progress method and to cancel the upload using the abort method. ```typescript const uploadTask = Taro.uploadFile({ url: 'https://example.weixin.qq.com/upload', //仅为示例,非真实的接口地址 filePath: tempFilePaths[0], name: 'file', formData:{ 'user': 'test' }, success: function (res){ var data = res.data //do something } }) uploadTask.progress((res) => { console.log('上传进度', res.progress) console.log('已经上传的数据长度', res.totalBytesSent) console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend) }) uploadTask.abort() // 取消上传任务 ``` -------------------------------- ### Initialize Project with Clone Option Source: https://github.com/nervjs/taro-docs/blob/master/docs/template.md Use the `--clone` option during `taro init` to specify fetching remote templates using `git clone`. ```sh taro init --clone ``` -------------------------------- ### Clone and Run Taro Native Shell Project Source: https://github.com/nervjs/taro-docs/blob/master/blog/2020-12-02-taro-3-2-0-cannary-1.md Clone the Taro native shell project from the specified GitHub repository and version. Install dependencies, including native iOS dependencies with `pod-install`, and then build and start the Android application. ```bash # Download the shell project $ git clone -b 0.63.2 git@github.com:NervJS/taro-native-shell.git # Install dependencies $ yarn # iOS requires installing native dependencies $ npx pod-install # Build and start the application $ yarn android -- --no-packager # When loaded successfully, you can see "Hello world" # If the IP or port number is inconsistent, you need to configure it yourself ``` -------------------------------- ### Map Component Usage with Event Handling Source: https://github.com/nervjs/taro-docs/blob/master/i18n/en/docusaurus-plugin-content-docs/current/components-desc.md Illustrates the usage of the Map component, which requires initial capitalization and camelCase naming. Event names must start with 'on'. This example shows a Map component with an onClick event handler. ```jsx import React, { Component } from 'react' import Taro from '@tarojs/taro' import { Map } from '@tarojs/components' class App extends Components { onTap () {} render () { return ( ) } } ``` -------------------------------- ### Register Platform and Start Build Source: https://github.com/nervjs/taro-docs/blob/master/i18n/en/docusaurus-plugin-content-docs/current/platform-plugin-base.md Register a custom platform with Taro using `ctx.registerPlatform` and initiate the build process by calling `program.start()`. ```typescript class Weapp extends TaroPlatformBase { // ... } export default (ctx) => { ctx.registerPlatform({ name: 'weapp', useConfigName: 'mini', async fn ({ config }) { const program = new Weapp(ctx, config) await program.start() } }) } ``` -------------------------------- ### Stop Voice Playback after Recording and Playing Source: https://github.com/nervjs/taro-docs/blob/master/docs/apis/media/audio/stopVoice.md This snippet demonstrates how to stop voice playback after starting a recording and playing it back. It uses a setTimeout to stop the voice after 5 seconds. This example uses the callback style for API calls. ```typescript Taro.startRecord({ success: function (res) { const filePath = res.tempFilePath Taro.playVoice({ filePath }) setTimeout(Taro.stopVoice, 5000) } }) ``` -------------------------------- ### Initialize New Taro Project with Canary Version Source: https://github.com/nervjs/taro-docs/blob/master/blog/2020-12-02-taro-3-2-0-cannary-1.md Use this command to create a new Taro project with the canary version of the CLI, selecting React as the framework. Ensure you have the canary version of `@tarojs/cli` installed globally. ```bash # Note: The latest version of @tarojs/cli has not been released yet, the trial version is under the canary tag $ yarn global add @tarojs/cli@canary # Create and initialize a Taro project, choose React as the framework $ taro init # Enter the initialized directory $ cd # Set the environment variable DEVTAG, the first time you use it, it will install the trial version related dependencies, which requires some waiting time # Supports specifying the port manually with the --port option $ DEVTAG=@canary yarn dev:rn --port 8081 # When the bundler starts successfully, the following information will be displayed # React-Native Dev server is running on port: 8081 ``` -------------------------------- ### Get Recorder Manager and Handle Events Source: https://github.com/nervjs/taro-docs/blob/master/docs/apis/media/recorder/getRecorderManager.md Obtain the global unique recorder manager and set up event listeners for start, pause, stop, and frame recording events. This snippet demonstrates how to initialize the recorder and handle the results of recording. ```typescript const recorderManager = Taro.getRecorderManager() recorderManager.onStart(() => { console.log('recorder start') }) recorderManager.onPause(() => { console.log('recorder pause') }) recorderManager.onStop((res) => { console.log('recorder stop', res) const { tempFilePath } = res }) recorderManager.onFrameRecorded((res) => { const { frameBuffer } = res console.log('frameBuffer.byteLength', frameBuffer.byteLength) }) const options = { duration: 10000, sampleRate: 44100, numberOfChannels: 1, encodeBitRate: 192000, format: 'aac', frameSize: 50 } recorderManager.start(options) ``` -------------------------------- ### Stop Voice Playback using Promises Source: https://github.com/nervjs/taro-docs/blob/master/docs/apis/media/audio/stopVoice.md This snippet shows how to stop voice playback using Promises, after starting a recording and playing it back. It utilizes setTimeout to stop the voice after 5 seconds. This example uses the Promise style for API calls. ```typescript Taro.startRecord(params).then(res => { const filePath = res.tempFilePath Taro.playVoice({ filePath }) setTimeout(Taro.stopVoice, 5000) }) ``` -------------------------------- ### Custom Metro Configuration for Taro RN Integration Source: https://github.com/nervjs/taro-docs/blob/master/blog/2021-04-08-taro-3.2.md Example of a custom Metro configuration file for integrating Taro into an existing React Native project. It uses `@tarojs/rn-supporter` to merge Taro's Metro configuration with the project's existing setup. ```javascript //metro.config.js 参考配置 const Supporter = require('@tarojs/rn-supporter') const supporter = new Supporter() const taroMetroConfig = supporter.getMetroConfig() const busConfig = { resetCache: true, } module.exports = mergeConfig(busConfig, taroMetroConfig) ``` -------------------------------- ### Stop Recording After Starting Source: https://github.com/nervjs/taro-docs/blob/master/docs/apis/media/recorder/stopRecord.md Starts recording audio and then stops it after a 10-second delay. This snippet demonstrates the basic usage of starting and stopping a recording. ```typescript Taro.startRecord({ success: function (res) { var tempFilePath = res.tempFilePath }, fail: function (res) { //录音失败 } }) setTimeout(function() { //结束录音 Taro.stopRecord() }, 10000) ``` -------------------------------- ### startCasting Source: https://github.com/nervjs/taro-docs/blob/master/docs/apis/media/live/LivePlayerContext.md Initiates screen casting by launching a half-screen device search. This method should only be called within a tap event callback and is supported on WeChat Mini Programs. ```APIDOC ## startCasting ### Description Starts screen casting by launching a half-screen device search. This method is intended for use within tap event callbacks. ### Method (option?: StartCastingOption) => void ### Parameters #### Path Parameters - **option** (StartCastingOption) - Required - The options for starting the casting session. ``` -------------------------------- ### Modularizing Components with Render Functions Source: https://github.com/nervjs/taro-docs/blob/master/docs/complier-mode.mdx This example demonstrates how to break down complex component rendering into smaller, manageable functions starting with 'render'. It utilizes Taro's semi-compilation mode with `compileMode="subRenderFn"` for optimized rendering of static nodes within these functions. This approach is useful for organizing component logic and improving performance by minimizing the number of compiled templates. ```jsx import { View, Image, Text } from "@tarojs/components"; import './index.scss' const dataList = [ { src: "https://media.tiffany.cn/is/image/Tiffany/EcomBrowseM/35189432_1009333_ED.jpg?defaultImage=NoImageAvailableInternal", title: "这是标题1", subTitle: "这是子标题1", tag:[ { name: "标签1", type: 1 }, { name: "标签2", type: 2 }, { name: "标签3", type: 3 } ], des: "这是描述1", subDes:'这是子描述1', prices: { normal: { int: '86', float: '88' }, line: 100 } }, { src: "https://media.tiffany.cn/is/image/Tiffany/EcomBrowseM/62866950_989218_ED.jpg?defaultImage=NoImageAvailableInternal", title: "这是标题2", subTitle: "这是子标题2", tag:[ { name: "标签1", type: 1 }, { name: "标签2", type: 2 }, { name: "标签3", type: 3 } ], tagType: 2, des: "这是描述2", subDes:'这是子描述2', prices: { normal: { int: '60', float: '70' }, line: 100 } }, { src: "https://media.tiffany.cn/is/image/Tiffany/EcomBrowseM/62507586_989743_ED_M.jpg?defaultImage=NoImageAvailableInternal", title: "这是标题3", subTitle: "这是子标题3", tag:[ { name: "标签1", type: 1 }, { name: "标签2", type: 2 }, { name: "标签3", type: 3 } ], des: "这是描述3", subDes:'这是子描述3', prices: { normal: { int: '85', float: '10' }, line: 100 } }, { src: "https://media.tiffany.cn/is/image/Tiffany/EcomBrowseM/33263465_997778_ED.jpg?defaultImage=NoImageAvailableInternal", title: "这是标题4", subTitle: "这是子标题4", tag:[ { name: "标签1", type: 1 }, { name: "标签2", type: 2 }, { name: "标签3", type: 3 } ], des: "这是描述4", subDes:'这是子描述4', prices: { normal: { int: '8', float: '88' }, line: 100 } }, { src: "https://media.tiffany.cn/is/image/Tiffany/EcomBrowseM/60957401_1023440_ED.jpg?defaultImage=NoImageAvailableInternal", title: "这是标题5", subTitle: "这是子标题5", tag:[ { name: "标签1", type: 1 }, { name: "标签2", type: 2 }, { name: "标签3", type: 3 } ], des: "这是描述5", subDes:'这是子描述5', prices: { normal: { int: '77', float: '88' }, line: 100 } } ] const Item = (props) =>{ const { itemIndex } = props const sectionIndex = itemIndex % 5 const data = dataList[sectionIndex] const { tag, src, title, subTitle, des, subDes, prices } = data const renderCard = ()=> { return ( {renderImage()} {renderContent()} ) } const renderImage = ()=> { return ( ) } const renderContent = () =>{ return ( {renderTitle()} {renderDes()} {renderTags(tag)} {renderPrices()} {renderBtn()} ) } const renderTitle = () =>{ return ( {title} {subTitle} ) } const renderDes = () => { return ( ``` -------------------------------- ### 快应用项目配置示例 Source: https://github.com/nervjs/taro-docs/blob/master/docs/quick-app.md 在 project.quickapp.json 文件中配置快应用应用的包名、名称、图标、版本信息等。此配置项用于适配 Taro 编译为快应用。 ```json { "customPageConfig": { "pages/index/index": { "filter": { "": { "uri": "" } }, "launchMode": "standard" } } } ``` -------------------------------- ### Verify Taro CLI Installation Source: https://github.com/nervjs/taro-docs/blob/master/docs/guide.mdx After installation, run the 'taro' command to verify the installation. A successful output will display the Taro version and available commands. ```bash taro ``` -------------------------------- ### Install Redux Dependencies Source: https://github.com/nervjs/taro-docs/blob/master/docs/redux.md Install the necessary Redux packages including redux, react-redux, redux-thunk, and redux-logger. Use either yarn or npm for installation. ```bash yarn add redux react-redux redux-thunk redux-logger # 或者使用 npm $ npm install --save redux react-redux redux-thunk redux-logger ``` -------------------------------- ### StartPreviewOption Source: https://github.com/nervjs/taro-docs/blob/master/i18n/en/docusaurus-plugin-content-docs/current/apis/media/live/LivePusherContext.md Options for the startPreview method. ```APIDOC ## StartPreviewOption ### Description Options for the startPreview method. ### Properties - **complete** (callback) - Optional - The callback function used when the API call completed (always executed whether the call succeeds or fails). - **fail** (callback) - Optional - The callback function for a failed API call. - **success** (callback) - Optional - The callback function for a successful API call. ``` -------------------------------- ### Initialize Taro Project v3.6 Source: https://github.com/nervjs/taro-docs/blob/master/blog/2023-02-01-Taro-3.6.md Install the latest CLI tools and create a new Taro project using version 3.6.0. ```bash # 安装 v3.6.0 的 CLI 工具 npm i -g @tarojs/cli@latest # 创建项目 taro init taro_project ``` -------------------------------- ### Install Webpack Bundle Analyzer Source: https://github.com/nervjs/taro-docs/blob/master/docs/guide.mdx Installs the webpack-bundle-analyzer package as a development dependency. ```bash npm install webpack-bundle-analyzer -D ``` -------------------------------- ### Compile and Preview Alipay Mini Program Source: https://github.com/nervjs/taro-docs/blob/master/blog/2018-11-05-taro-1-1.md Similar to Baidu Smart Mini Program, these commands facilitate compilation and watching for Alipay Mini Program development. ```bash # npm script $ npm run dev:alipay $ npm run build:alipay # Global installation only $ taro build --type alipay --watch $ taro build --type alipay # npx users can also use $ npx taro build --type alipay --watch $ npx taro build --type alipay ``` -------------------------------- ### LivePusherContext.startPreview Source: https://github.com/nervjs/taro-docs/blob/master/i18n/en/docusaurus-plugin-content-docs/current/apis/media/live/LivePusherContext.md Starts the preview of the live pusher. This method is supported on WeChat Mini-Program. ```APIDOC ## LivePusherContext.startPreview ### Description Starts the preview of the live pusher. ### Method Not applicable (SDK method) ### Endpoint Not applicable (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response None #### Response Example None ``` -------------------------------- ### Install Webpack5 Runner Source: https://github.com/nervjs/taro-docs/blob/master/blog/2022-07-26-Taro-3.5.md Install the `@tarojs/webpack5-runner` package to enable Webpack 5 compilation. ```bash npm install @tarojs/webpack5-runner ``` -------------------------------- ### Open Jingdong Mini-program using Page Alias Source: https://github.com/nervjs/taro-docs/blob/master/i18n/en/docusaurus-plugin-content-docs/current/app-config.md Example of using the 'openapp' protocol to open a Jingdong mini-program page via its alias. This requires specific app and engine versions. ```bash openapp.jdmobile://virtual?params={"category":"jump","des":"jdmp","appId":"ao123","vapptype":"1","path":"","pageAlias":"my","param":{}} ``` -------------------------------- ### Install HTML Plugin Source: https://github.com/nervjs/taro-docs/blob/master/blog/2021-08-13-Taro-3.3.md Install the @tarojs/plugin-html package to enable H5 tag support. ```bash $ npm i @tarojs/plugin-html ``` -------------------------------- ### Start Gyroscope Listening Source: https://github.com/nervjs/taro-docs/blob/master/i18n/en/docusaurus-plugin-content-docs/current/apis/device/gyroscope/startGyroscope.md Starts listening for gyroscope data. You can specify the interval for data updates. ```typescript Taro.startGyroscope({ interval: 'normal' // 'game' | 'ui' | 'normal' }).then(res => { console.log('startGyroscope success', res) }).catch(err => { console.log('startGyroscope fail', err) }) ``` -------------------------------- ### Create New Taro Project with npx Source: https://github.com/nervjs/taro-docs/blob/master/blog/2023-02-01-Taro-3.6.md Use this command to initialize a new Taro project without installing the CLI globally. ```bash npx @tarojs/cli@latest init taro_project ``` -------------------------------- ### Icon Examples in React Source: https://github.com/nervjs/taro-docs/blob/master/i18n/en/docusaurus-plugin-content-docs/current/components/base/icon.md Demonstrates how to use the Icon component with different types, sizes, and colors in a React environment. Ensure the Icon component is imported. ```tsx import Taro from '@tarojs/taro' import { Component } from '@tarojs/taro' import { View, Icon } from '@tarojs/components' export default class PageView extends Component { constructor() { super(...arguments) } render() { return ( ) } } ``` -------------------------------- ### React Button Examples Source: https://github.com/nervjs/taro-docs/blob/master/i18n/en/docusaurus-plugin-content-docs/current/components/forms/button.md Demonstrates various button configurations including primary, secondary, warn types, loading, disabled states, and different sizes in a React environment. ```tsx export default class PageButton extends Component { state = { btn: [ { text: 'Primary Normal', size: 'default', type: 'primary' }, { text: 'Primary Loading', size: 'default', type: 'primary', loading: true, }, { text: 'Primary Disabled', size: 'default', type: 'primary', disabled: true, }, { text: 'Secondary Normal', size: 'default', type: 'default' }, { text: 'Secondary Disabled', size: 'default', type: 'default', disabled: true, }, { text: 'Wran Normal', size: 'default', type: 'warn' }, { text: 'Wran Disabled', size: 'default', type: 'warn', disabled: true, } ] } render () { return ( {this.state.btn.map(item => { return ( ) })} ) } } ``` -------------------------------- ### Build H5 App with Taro Source: https://github.com/nervjs/taro-docs/blob/master/blog/2020-05-26-taro-3-rc.md Install the H5 runner and build your Taro project for the web. Use the --watch flag for live updates. ```bash npm i -D @tarojs/webpack-runner@next taro build —type h5 —watch ``` -------------------------------- ### Install Vue3 JSX Support Source: https://github.com/nervjs/taro-docs/blob/master/blog/2022-07-26-Taro-3.5.md For projects using Vue 3, install `@vue/babel-plugin-jsx` to enable JSX support. ```bash npm i @vue/babel-plugin-jsx --save-dev ``` -------------------------------- ### Install Vue2 JSX Support Source: https://github.com/nervjs/taro-docs/blob/master/blog/2022-07-26-Taro-3.5.md For projects using Vue 2, install `@vue/babel-preset-jsx` to enable JSX support. ```bash npm i @vue/babel-preset-jsx --save-dev ``` -------------------------------- ### Start HTTP Server for Release Debugging Source: https://github.com/nervjs/taro-docs/blob/master/docs/react-native.md Starts an HTTP server and prints a QR code for debugging release bundles with Taro Playground APP. Note that Android and iOS require separate verification. ```shell yarn build:rn --qr --platform ios ``` -------------------------------- ### Install Preact Refresh Dependencies Source: https://github.com/nervjs/taro-docs/blob/master/blog/2022-07-26-Taro-3.5.md For projects using Preact, install `@prefresh/webpack` and `@prefresh/babel-plugin` for development hot reloading. ```bash npm i @prefresh/webpack @prefresh/babel-plugin --save-dev ``` -------------------------------- ### Tab Bar Configuration Example Source: https://github.com/nervjs/taro-docs/blob/master/i18n/en/docusaurus-plugin-content-docs/current/apis/route/switchTab.md This JSON snippet shows a basic configuration for the tabBar in app.json, defining the pages that will appear in the application's tab bar. ```json { "tabBar": { "list": [{ "pagePath": "index", "text": "Home" },{ "pagePath": "other", "text": "Other" }] } } ``` -------------------------------- ### Install React Refresh Dependencies Source: https://github.com/nervjs/taro-docs/blob/master/blog/2022-07-26-Taro-3.5.md For projects using React, install `@pmmmwh/react-refresh-webpack-plugin` and `react-refresh` for development hot reloading. ```bash npm i @pmmmwh/react-refresh-webpack-plugin react-refresh --save-dev ``` -------------------------------- ### Taro.openSetting Source: https://github.com/nervjs/taro-docs/blob/master/i18n/en/docusaurus-plugin-content-docs/current/apis/open-api/settings/openSetting.md Opens the Mini Program settings interface on WeChat. This function returns a Promise that resolves with the authorization settings. Note that only permissions previously requested by the Mini Program are displayed. ```APIDOC ## Taro.openSetting(option) ### Description Opens the Mini Program settings interface on WeChat and returns setting results. Only permissions that have been requested by the Mini Program from the user are displayed on the settings interface. ### Method ```typescript (option?: Option) => Promise ``` ### Parameters #### Option - **complete** ((res: any) => void) - Optional - The callback function used when the API call completed (always executed whether the call succeeds or fails) - **fail** ((res: any) => void) - Optional - The callback function for a failed API call - **success** ((res: Result) => void) - Optional - The callback function for a successful API call #### SuccessCallbackResult - **authSetting** (AuthSetting) - Results of user authorization - **errMsg** (string) - Call result ### Sample Code ```tsx Taro.openSetting({ success: function (res) { console.log(res.authSetting) } }) ``` ``` -------------------------------- ### Install Next Taro CLI Source: https://github.com/nervjs/taro-docs/blob/master/blog/2020-12-15-taro-3-1-beta.md Install the next version of the Taro CLI globally to upgrade to version 3.1. ```bash npm i -g @tarojs/cli@next ```