### Install Dependencies and Start Dev Server Source: https://docs.taro.zone/docs/CONTRIBUTING-GUIDE Install project dependencies and start the local development server for previewing documentation changes. Run these commands from the root of the cloned repository. ```bash $ pnpm install $ pnpm run start ``` -------------------------------- ### Install Vuex Source: https://docs.taro.zone/docs/guide Install Vuex for state management in a Vue-based Taro project. ```bash npm i vuex ``` -------------------------------- ### Install Alipay IoT Mini Program Plugin Source: https://docs.taro.zone/docs/GETTING-STARTED Install the Taro plugin for compiling Alipay IoT mini programs. Ensure Taro v3.1+ is installed. ```bash yarn add @tarojs/plugin-platform-alipay-iot ``` -------------------------------- ### Start Development Debugging Server Source: https://docs.taro.zone/docs/react-native Run this command to start the metro server and print a QR code for development debugging with Taro Playground. ```bash yarn dev:rn --qr ``` -------------------------------- ### Share Element Example Source: https://docs.taro.zone/docs/components/skyline/share-element This example showcases the ShareElement component for animating element transitions between screens. It includes setup for contacts, state management for visibility and selected contact, and event handlers for the transition lifecycle. ```javascript // index.js import { useState, useCallback } from 'react' import { View, Button, PageContainer, ShareElement } from '@tarojs/components' import './index.scss' const contacts = [ { id: 1, name: 'Frank', img: 'frank.png', phone: '0101 123456', mobile: '0770 123456', email: 'frank@emailionicsorter.com' }, { id: 2, name: 'Susan', img: 'susan.png', phone: '0101 123456', mobile: '0770 123456', email: 'frank@emailionicsorter.com' }, { id: 3, name: 'Emma', img: 'emma.png', phone: '0101 123456', mobile: '0770 123456', email: 'frank@emailionicsorter.com' }, { id: 4, name: 'Scott', img: 'scott.png', phone: '0101 123456', mobile: '0770 123456', email: 'frank@emailionicsorter.com' }, { id: 5, name: 'Bob', img: 'bob.png', phone: '0101 123456', mobile: '0770 123456', email: 'frank@emailionicsorter.com' }, { id: 6, name: 'Olivia', img: 'olivia.png', phone: '0101 123456', mobile: '0770 123456', email: 'frank@emailionicsorter.com' }, { id: 7, name: 'Anne', img: 'anne.png', phone: '0101 123456', mobile: '0770 123456', email: 'frank@emailionicsorter.com' }, { id: 8, name: 'sunny', img: 'olivia.png', phone: '0101 123456', mobile: '0770 123456', email: 'frank@emailionicsorter.com' } ] export default function () { const [show, setShow] = useState(false) const [contact, setContact] = useState(contacts[0]) const [transformIdx, setTransformIdx] = useState(0) const onBeforeEnter = useCallback((res) => { console.log('onBeforeEnter: ', res) }, []) const onEnter = useCallback((res) => { console.log('onEnter: ', res) }, []) const onAfterEnter = useCallback((res) => { console.log('onAfterEnter: ', res) }, []) const onBeforeLeave = useCallback((res) => { console.log('onBeforeLeave: ', res) }, []) const onLeave = useCallback((res) => { console.log('onLeave: ', res) }, []) const onAfterLeave = useCallback((res) => { console.log('onAfterLeave: ', res) }, []) const showNext = (e, index) => { setShow(true) setContact(contacts[index]) setTransformIdx(index) } const showPrev = useCallback(() => { setShow(false) }, []) return ( { contacts.map((item, index) => ( showNext(e, index)}> {item.name} Phone: {item.phone} Mobile: {item.mobile} Email: {item.email} )) } {contact.name} Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus nisl enim, sodales non augue efficitur, sagittis varius neque. Fusce dolor turpis, maximus eu volutpat quis, pellentesque et ligula. Ut vehicula metus in nibh mollis ornare. Etiam aliquam lacinia malesuada. Vestibulum dignissim mollis quam a tristique. Maecenas neque mauris, malesuada vitae magna eu, congue consectetur risus. Etiam vitae pulvinar ex. Maecenas suscipit mi ac imperdiet pretium. Aliquam velit mauris, euismod quis elementum sed, malesuada non dui. Nunc rutrum sagittis ligula in dapibus. Cras suscipit ut augue eget mollis. Donec auctor feugiat ipsum id viverra. Vestibulum eu nisi risus. Vestibulum eleifend dignissim. ) } ``` -------------------------------- ### Start Release Debugging Server Source: https://docs.taro.zone/docs/react-native Run this command to start an HTTP server and print a QR code for release bundle debugging. Note that Android and iOS require separate verification. ```bash yarn build:rn --qr --platform ios ``` -------------------------------- ### Install Lark Mini Program Plugin Source: https://docs.taro.zone/docs/GETTING-STARTED Install the Taro plugin for compiling Lark mini programs. Ensure Taro v3.1+ is installed. ```bash yarn add @tarojs/plugin-platform-lark ``` -------------------------------- ### Install Redux and React-Redux Source: https://docs.taro.zone/docs/guide Install the necessary packages for Redux state management in a React-based Taro project. ```bash npm i redux react-redux ``` -------------------------------- ### StartCastingOption Source: https://docs.taro.zone/docs/apis/media/live/LivePlayerContext Options for starting a casting session. ```APIDOC ## StartCastingOption ### Description Options for starting a casting session. ### Parameters #### Optional Parameters - **complete** ( (res: TaroGeneral.CallbackResult) => void ) - Callback function executed when the API call ends (whether successful or failed). - **fail** ( (res: TaroGeneral.CallbackResult) => void ) - Callback function executed when the API call fails. - **success** ( (res: TaroGeneral.CallbackResult) => void ) - Callback function executed when the API call succeeds. ``` -------------------------------- ### Taro Next Project File Structure Example Source: https://docs.taro.zone/docs/migration An example illustrating the file structure for a Taro Next project, showing the placement of `app.config.js` and `index.config.js`. ```plaintext . ├── app.config.js // 入口文件项目配置 ├── app.js ├── app.scss ├── components │ └── result.js // 组件若不使用第三方组件则无需配置 └── pages └── index ├── index.config.js // index 的页面配置 └── index.js ``` -------------------------------- ### startAdvertising Source: https://docs.taro.zone/docs/apis/device/bluetooth-peripheral/BLEPeripheralServer Starts advertising the BLE peripheral device with specified parameters. ```APIDOC ## startAdvertising ### Description Starts the advertising process for the BLE peripheral device, allowing it to be discovered by other devices. ### Parameters #### Option - **advertiseRequest** (advertiseRequest) - Required - Custom parameters for the broadcast. - **powerLevel** (keyof PowerLevel) - Optional - Defaults to `"medium"`. The broadcast power level. - **complete** ( (res: TaroGeneral.BluetoothError) => void ) - Optional - Callback function executed when the interface call ends (both success and failure). - **fail** ( (res: TaroGeneral.BluetoothError) => void ) - Optional - Callback function executed when the interface call fails. - **success** ( (res: TaroGeneral.BluetoothError) => void ) - Optional - Callback function executed when the interface call succeeds. #### advertiseRequest - **connectable** (boolean) - Optional - Defaults to `true`. Indicates if the device is connectable. - **deviceName** (string) - Optional - Defaults to `""`. The `deviceName` field in the broadcast, defaults to empty. - **serviceUuids** (string[]) - Optional - A list of service UUIDs to broadcast. Refer to the notes for 16/32-bit UUIDs. - **manufacturerData** (manufacturerData[]) - Optional - Broadcast manufacturer information. Only supported on Android; iOS cannot customize due to system limitations. - **beacon** (beacon) - Optional - Parameters for broadcasting as a beacon device. #### manufacturerData - **manufacturerId** (string) - Required - Manufacturer ID, hexadecimal starting with `0x`. - **manufacturerSpecificData** (ArrayBuffer) - Optional - Manufacturer-specific data. #### beacon - **uuid** (string) - Required - The UUID broadcast by the beacon device. - **major** (number) - Required - The major ID of the beacon device. - **minor** (number) - Required - The minor ID of the beacon device. - **measuredPower** (number) - Optional - Reference value for RSSI at 1 meter from the device, used for distance estimation. #### PowerLevel - **low** - Low power. - **medium** - Medium power. - **high** - High power. ``` -------------------------------- ### Install Enterprise WeChat Mini Program Plugin Source: https://docs.taro.zone/docs/GETTING-STARTED Install the Taro plugin for compiling enterprise WeChat mini programs. Ensure Taro v3.1+ is installed. ```bash yarn add @tarojs/plugin-platform-weapp-qy ``` -------------------------------- ### Install Webpack Bundle Analyzer Source: https://docs.taro.zone/docs/guide Install `webpack-bundle-analyzer` as a development dependency to analyze your application's bundle size. ```bash npm install webpack-bundle-analyzer -D ``` -------------------------------- ### TaroWebContainer Integration Example Source: https://docs.taro.zone/docs/harmony/hybrid This example demonstrates how to use the TaroWebContainer component in an Ets page to load a web application. It includes setup for page state, controller, and injecting custom objects into the web environment. Configure the webUrl to point to your application's entry point. ```typescript import Want from '@ohos.app.ability.Want'; import Url from '@ohos.url'; import { TaroWebContainer, InjectObject, HostPageState, TaroWebController } from '@hybrid/web-container'; const WEB_CONTAINER_PAGE_TAG = 'WebContainerPage'; let storage = LocalStorage.getShared() // 获取共享的本地存储对象 const TAG = 'WebContainerPage'; @Entry(storage) @Component struct WebContainerPage { @LocalStorageProp('want') want: Want = {}; @State pageState: HostPageState = HostPageState.PageInit; @State taroWebController: TaroWebController = new TaroWebController(); // 用户可以自定义对象注入到Web环境中,使用native.sayHello格式进行调用 nativeObj: InjectObject = { sayHello: () => console.log(TAG, 'sayHello %{public}s', 'Hello World'), } onBackPress() { if (this.taroWebController.accessBackward()) { this.taroWebController.backward(); return true; } return false; } onPageShow() { this.pageState = HostPageState.PageOnShow; } onPageHide() { this.pageState = HostPageState.PageOnHide; } webUrl(): string { // 开发阶段可以把网站静态资源文件放置到src/main/resources/rawfile/目录下 // 生产环境下把网站静态资源放置到web服务器, 这里填写实际的网站地址url return 'resource://rawfile/index.html'; } webUrlPrefix() { try { const url = Url.URL.parseURL(this.webUrl()); return `${url.protocol}//${url.host}/`; } catch (err) { console.error(WEB_CONTAINER_PAGE_TAG, `Invalid webUrl: ${this.webUrl()}`); return ''; } } getUrl(value: LoadCommittedDetails) { console.log('LoadCommittedDetails:', JSON.stringify(value)) } build() { Column() { TaroWebContainer({ indexHtmlPath: 'index.html', pageState: this.pageState, // 页面状态同步到组件 webUrl: this.webUrl(), // 初始Url webUrlPrefix: this.webUrlPrefix(), useCache: false, want: this.want, // want信息 taroWebController: this.taroWebController, isFullScreen: false, // 是否全屏显示 injectObj: this.nativeObj, // 注入对象 navigationInitVisible: true, // 导航栏是否显示 showCapsule:true, capsulePage:'index.html', enableWebDebug:true, forceDarkAccess: true, userAgent: '', getLoadCommittedDetails: (value: LoadCommittedDetails) => { this.getUrl(value) } }) .width('100%') .height('100%') } } } ``` -------------------------------- ### React: Virtual Waterfall Component Setup Source: https://docs.taro.zone/docs/virtual-waterfall Demonstrates the setup of a Virtual Waterfall component in a React class component. It shows how to create a ref to access the component's methods and render the list with essential props. ```jsx export default class Index extends Component { state = { data: buildData(0), } list = React.createRef() componentDidMount() { const list = this.list.current list.scrollTo() list.scrollToItem() } render() { const { data } = this.state const dataLen = data.length return ( ) } } ``` -------------------------------- ### MobX Store Setup Variants Source: https://docs.taro.zone/docs/mobx Demonstrates different ways to set up multiple stores with the Provider component in @tarojs/mobx compared to mobx-react. ```javascript ``` ```javascript const store = { store1: xxxx, store2: xxxx } ``` -------------------------------- ### Handlebars Template Example Source: https://docs.taro.zone/docs/template An example of using Handlebars syntax within a template file, demonstrating conditional imports based on TypeScript usage. ```handlebars import { defineConfig{{#if typescript }}, type UserConfigExport{{/if}} } from '@tarojs/cli' {{#if typescript }}import TsconfigPathsPlugin from 'tsconfig-paths-webpack-plugin'{{/if}} ``` -------------------------------- ### Install DingTalk Mini Program Plugin Source: https://docs.taro.zone/docs/GETTING-STARTED Install the Taro plugin for compiling DingTalk mini programs. Use version `~0.1.0` for Taro v3.3.8+ or `~0.0.5` for Taro v3.1 & v3.2. ```bash yarn add @tarojs/plugin-platform-alipay-dd ``` -------------------------------- ### Registering a Compilation Platform (Alipay) Source: https://docs.taro.zone/docs/plugin-custom Example of registering the 'alipay' platform using ctx.registerPlatform. It configures the miniRunner options for Alipay's mini-program compilation. ```javascript ctx.registerPlatform({ name: 'alipay', useConfigName: 'mini', async fn({ config }) { const { appPath, nodeModulesPath, outputPath } = ctx.paths const { npm, emptyDirectory } = ctx.helper emptyDirectory(outputPath) // 准备 miniRunner 参数 const miniRunnerOpts = { ...config, nodeModulesPath, buildAdapter: config.platform, isBuildPlugin: false, globalObject: 'my', fileType: { templ: '.awml', style: '.acss', config: '.json', script: '.js', }, isUseComponentBuildPage: false, } // build with webpack const miniRunner = await npm.getNpmPkg('@tarojs/mini-runner', appPath) await miniRunner(appPath, miniRunnerOpts) }, }) ``` -------------------------------- ### Install WASM Target for SWC Plugins Source: https://docs.taro.zone/docs/CONTRIBUTING-GUIDE Install the wasm32-wasi target required for developing SWC plugins. This command should be run from the project root. ```bash # 执行所有 SWC 插件的单元测试 $ cargo test-swc-plugins # 执行某个 SWC 插件的单元测试 $ cargo test -p [package-name] ``` -------------------------------- ### MediaQueryObserver.observe Source: https://docs.taro.zone/docs/apis Starts listening for changes in media query conditions. ```APIDOC ## MediaQueryObserver.observe ### Description Starts listening for changes in media query conditions. ### Method `MediaQueryObserver.observe(mediaQueryString)` ### Parameters #### Path Parameters - **mediaQueryString** (string) - Required - The media query string to observe. ``` -------------------------------- ### Global Store Setup with Provider Source: https://docs.taro.zone/docs/mobx Set up the global MobX store in the entry file (src/app.js) using the Provider component. Only one Provider is supported and it cannot be nested. ```javascript import Taro, { Component } from '@tarojs/taro' import { Provider } from '@tarojs/mobx' import Index from './pages/index' import counterStore from './store/counter' const store = { counterStore, } class App extends Component { config = { pages: ['pages/index/index'], window: { backgroundTextStyle: 'light', navigationBarBackgroundColor: '#fff', navigationBarTitleText: 'WeChat', navigationBarTextStyle: 'black', }, } render() { return ( ) } } Taro.render(, document.getElementById('app')) ``` -------------------------------- ### VKSession.start Source: https://docs.taro.zone/docs/apis/ai/visionkit/VKSession Starts the VisionKit session. Supported on WeChat Mini Programs. ```APIDOC ## VKSession.start ### Description Starts the VisionKit session, initializing the necessary components and beginning the processing of camera input. ### Supported Platforms - WeChat Mini Program: Yes ``` -------------------------------- ### Configure Metro Default Configuration Source: https://docs.taro.zone/docs/react-native Example of how to access and potentially extend Taro's default Metro configuration for custom metro configurations. ```javascript const { defaultConfig } = require('@tarojs/rn-runner/dist/config') ``` -------------------------------- ### Fill Path with Default Closure Source: https://docs.taro.zone/docs/apis/canvas/CanvasContext Demonstrates the `fill()` method. If the current path is not closed, `fill()` will connect the start and end points before filling. ```javascript const ctx = Taro.createCanvasContext('myCanvas') ctx.moveTo(10, 10) ctx.lineTo(100, 10) ctx.lineTo(100, 100) ctx.fill() ctx.draw() ``` -------------------------------- ### Build Android Release Package (CI) Source: https://docs.taro.zone/docs/react-native Steps to build an Android release package using GitHub Actions. Ensure Ruby bundler is installed on Linux or macOS. ```bash yarn ``` ```bash yarn build:rn --platform android ``` ```bash linux: sudo apt install -y ruby-bundler, mac: gem install bundler ``` ```bash cd android && bundle update && bundle exec fastlane assemble ``` -------------------------------- ### Draw Image on Canvas Source: https://docs.taro.zone/docs/apis/canvas/CanvasContext Shows how to draw an image onto the canvas using `drawImage`. This example uses `Taro.chooseImage` to get an image resource and then draws it at specified coordinates and dimensions. ```javascript const ctx = Taro.createCanvasContext('myCanvas') Taro.chooseImage({ success: function(res){ ctx.drawImage(res.tempFilePaths[0], 0, 0, 150, 100) ctx.draw() } }) ``` ```javascript const ctx = Taro.createCanvasContext('myCanvas') Taro.chooseImage({ success: function(res){ ctx.drawImage(res.tempFilePaths[0], 0, 0, 150, 100) ctx.draw() } }) ``` ```javascript const ctx = Taro.createCanvasContext('myCanvas') Taro.chooseImage({ success: function(res){ ctx.drawImage(res.tempFilePaths[0], 0, 0, 150, 100) ctx.draw() } }) ``` -------------------------------- ### Manipulating Taro Element Refs Source: https://docs.taro.zone/docs/migration Shows how to use React's createRef to get a Taro Element instance and manipulate its properties and attributes directly. This example also illustrates how to obtain the native mini-program DOM instance using Taro.createSelectorQuery. ```javascript class C extends Component { input = React.createRef() componentDidMount() { const node = this.input.current // node 是一个 Taro Element 实例 node.focus() // ok, 在 Web 开发中常见做法 // 以下写法也能更新视图,但不推荐这么做,更推荐使用数据来驱动视图更新 node.setAttribute('class', 'input-css-class') node.className = 'input-css-class' node.style.fontSize = '16px' node.value = 'excited!' // 如果你需要获取原生小程序 DOM 的话 const miniNode = Taro.createSelectorQuery().select('#' + node.id) } render() { return } } ``` -------------------------------- ### Build Android Release Package (Manual) Source: https://docs.taro.zone/docs/react-native Steps to build an Android release package without using a CI tool. This involves running Gradle directly. ```bash yarn ``` ```bash yarn build:rn --platform android ``` ```bash cd android && ./gradlew assembleRelease ``` -------------------------------- ### Configure PostCSS Plugins for Mini Programs Source: https://docs.taro.zone/docs/config-detail Customize autoprefixer, pxtransform, and CSS Modules for mini program builds. Ensure correct configuration for each plugin based on its documentation. ```javascript module.exports = { // ... mini: { // ... postcss: { // 可以进行 autoprefixer 的配置。配置项参考官方文档 https://github.com/postcss/autoprefixer autoprefixer: { enable: true, config: { // autoprefixer 配置项 }, }, pxtransform: { enable: true, config: { // pxtransform 配置项,参考尺寸章节 selectorBlackList: ['body'], }, }, // 小程序端样式引用本地资源内联 该属性在 v4.0.0 版本已废弃,小程序端默认全部转换 // url: { // enable: true, // config: { // maxSize: 10, // 设定转换尺寸上限(单位:kbytes) // }, // }, // css modules 功能开关与相关配置 cssModules: { enable: false, // 默认为 false,如需使用 css modules 功能,则设为 true config: { generateScopedName: '[name]__[local]___[hash:base64:5]', }, }, }, }, } ``` -------------------------------- ### val Source: https://docs.taro.zone/docs/jquery-like Gets or sets the value of the matched elements. When getting, returns the value of the first element. When setting, sets the value for all elements. ```APIDOC ## val ### Description Gets or sets the value of the matched elements. ### Method `val()` `val(value)` `val(function(index, oldValue){ ... })` ### Parameters - **value** (string | number | boolean | function, optional) - The value to set, or a function that returns the value. ### Returns - `string` - When getting the value. - `self` - When setting the value. ``` -------------------------------- ### Compile QQ Mini Program Source: https://docs.taro.zone/docs/GETTING-STARTED Commands to develop and build QQ mini programs using pnpm, yarn, or npm scripts. Global installation and npx users can also use `taro build` commands. Production builds can be combined with watch mode. ```bash # pnpm $ pnpm dev:qq $ pnpm build:qq # yarn $ yarn dev:qq $ yarn build:qq # npm script $ npm run dev:qq $ npm run build:qq # 仅限全局安装 $ taro build --type qq --watch $ taro build --type qq # npx 用户也可以使用 $ npx taro build --type qq --watch $ npx taro build --type qq # watch 同时开启压缩 $ set NODE_ENV=production && taro build --type qq --watch # CMD $ NODE_ENV=production taro build --type qq --watch # Bash ``` -------------------------------- ### Create and Play Audio Source: https://docs.taro.zone/docs/apis/media/audio/InnerAudioContext Demonstrates how to create an InnerAudioContext, set its source, and handle playback events. This is useful for initiating audio playback with custom event listeners for play and error states. ```javascript const innerAudioContext = Taro.createInnerAudioContext() innerAudioContext.autoplay = true innerAudioContext.src = 'https://ws.stream.qqmusic.qq.com/M500001VfvsJ21xFqb.mp3?guid=ffffffff82def4af4b12b3cd9337d5e7&uin=346897220&vkey=6292F51E1E384E061FF02C31F716658E5C81F5594D561F2E88B854E81CAAB7806D5E4F103E55D33C16F3FAC506D1AB172DE8600B37E43FAD&fromtag=46' innerAudioContext.onPlay(() => { console.log('开始播放') }) innerAudioContext.onError((res) => { console.log(res.errMsg) console.log(res.errCode) }) ``` -------------------------------- ### useReducer Counter Example Source: https://docs.taro.zone/docs/hooks A counter example rewritten using useReducer. The reducer function handles different action types to update the state. ```javascript const initialState = { count: 0 } function reducer(state, action) { switch (action.type) { case 'increment': return { count: state.count + 1 } case 'decrement': return { count: state.count - 1 } default: throw new Error() } } function Counter({ initialState }) { const [state, dispatch] = useReducer(reducer, initialState) return ( Count: {state.count} ) } ``` -------------------------------- ### Compile Alipay IoT Mini Program Source: https://docs.taro.zone/docs/GETTING-STARTED Commands to develop and build Alipay IoT mini programs using pnpm, yarn, or npm scripts. Global installation and npx users can also use `taro build` commands. Production builds can be combined with watch mode. ```bash # pnpm $ pnpm dev:iot $ pnpm build:iot # yarn $ yarn dev:iot $ yarn build:iot # npm script $ npm run dev:iot $ npm run build:iot # 仅限全局安装 $ taro build --type iot --watch $ taro build --type iot # npx 用户也可以使用 $ npx taro build --type iot --watch $ npx taro build --type iot # watch 同时开启压缩 $ set NODE_ENV=production && taro build --type iot --watch # CMD $ NODE_ENV=production taro build --type iot --watch # Bash ``` -------------------------------- ### Ignore Specific CSS Properties Example Source: https://docs.taro.zone/docs/size This example shows a common text truncation style that might require specific properties to be ignored during compilation. ```css .textHide { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; text-overflow: ellipsis; overflow: hidden; } ``` -------------------------------- ### Build iOS Release Package (Manual) Source: https://docs.taro.zone/docs/react-native Steps to build an iOS release package without using a CI tool. This involves using Xcode for packaging. ```bash yarn ``` ```bash yarn build:rn --platform ios ``` ```bash Use Xcode to package ``` -------------------------------- ### text Source: https://docs.taro.zone/docs/jquery-like Gets or sets the text content of the elements in the collection. When getting, it returns the text content of the first element. When setting, it replaces the text content of all elements. ```APIDOC ## text ### Description Gets or sets the text content of the elements in the collection. ### Method `text()` `text(content)` `text(function(index, oldText){ ... })` ### Parameters - **content** (string | function, optional) - The text content to set, or a function that returns the text content. ### Returns - `string` - When getting text content. - `self` - When setting text content. ``` -------------------------------- ### Run NAPI Binding Tests Source: https://docs.taro.zone/docs/CONTRIBUTING-GUIDE Execute unit tests for the NAPI bindings. Ensure you are in the project root directory. ```bash $ pnpm --filter @tarojs/binding run test ``` -------------------------------- ### Manual Peer Dependency Installation Source: https://docs.taro.zone/docs/react-native Manually install peer dependencies for core Taro React Native packages and run pod-install. Use this if `yarn upgradePeerdeps` fails. ```bash install-peerdeps @tarojs/taro-rn -o -Y && install-peerdeps @tarojs/components-rn -o -Y && install-peerdeps @tarojs/router-rn -o -Y && pod-install ``` -------------------------------- ### ctx.generateFrameworkInfo({ platform: string }) Source: https://docs.taro.zone/docs/plugin-custom Generates a .frameworkinfo file, which contains compilation information for a specified platform. ```APIDOC ## ctx.generateFrameworkInfo({ platform: string }) ### Description Generates a `.frameworkinfo` file containing compilation information for a specified platform. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **platform** (string) - Required - The name of the platform for which to generate the framework info. ### Request Example ```json ctx.generateFrameworkInfo({ platform: 'reactNative' }) ``` ### Response None #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Get Node Size in React Source: https://docs.taro.zone/docs/ref Use Taro.createSelectorQuery within the useReady hook to get node bounding client rect information after the component is ready. Ensure the target element has an ID. ```javascript import { View } from '@tarojs/components' import Taro, { useReady } from '@tarojs/taro' export default function Index () { useReady(() => { // 初次渲染时,在小程序触发 onReady 后,才能获取小程序的渲染层节点 Taro.createSelectorQuery() .select('#target') .boundingClientRect() .exec(res => console.log(res)) }) return ( ) } ``` -------------------------------- ### Configure Taro Plugins With Parameters Source: https://docs.taro.zone/docs/config-detail Integrate Taro plugins and pass configuration parameters to them. This example demonstrates how to provide custom mock data to the '@tarojs/plugin-mock' plugin for API request mocking. ```javascript module.exports = { // ... plugins: [ // 引入 npm 安装的插件,并传入插件参数 [ '@tarojs/plugin-mock', { mocks: { '/api/user/1': { name: 'judy', desc: 'Mental guy', }, }, }, ], ], } ``` -------------------------------- ### Get Node Size in Child Component (React) Source: https://docs.taro.zone/docs/ref To get node information from a child component in React, use the useReady hook within the child component. The target element must have an ID. ```javascript import { View } from '@tarojs/components' import Taro, { useReady } from '@tarojs/taro' function Comp () { useReady(() => { // 初次渲染时,在小程序触发 onReady 后,才能获取小程序的渲染层节点 Taro.createSelectorQuery() .select('#target') .boundingClientRect() .exec((res) => console.log(res)) }) return ( ) } export default function Index () { return ( ) } ``` -------------------------------- ### Configure Taro Plugins Without Parameters Source: https://docs.taro.zone/docs/config-detail Add Taro plugins to your project configuration. This example shows how to include plugins by their absolute path or npm package name, without passing any specific parameters. ```javascript module.exports = { // ... plugins: [ // 从本地绝对路径引入插件 '/absulute/path/plugin/filename', // 引入 npm 安装的插件 '@tarojs/plugin-mock', ['@tarojs/plugin-mock'], ['@tarojs/plugin-mock', {}], ], } ``` -------------------------------- ### size Source: https://docs.taro.zone/docs/jquery-like Gets the number of elements in the collection. ```APIDOC ## size ### Description Gets the number of elements in the collection. ### Method `size()` ### Returns - `number` - The number of elements. ``` -------------------------------- ### Build iOS Release Package (CI) Source: https://docs.taro.zone/docs/react-native Steps to build an iOS release package using GitHub Actions. Ensure pods are installed and the environment variable SKIP_BUNDLING is set. ```bash yarn ``` ```bash yarn build:rn --platform ios ``` ```bash npx pod-install ``` ```bash export SKIP_BUNDLING=1 ``` ```bash cd ios && bundle update && bundle exec fastlane build_release ``` -------------------------------- ### Registering a Custom Command Source: https://docs.taro.zone/docs/plugin-custom Shows how to register a custom command using ctx.registerCommand. This includes defining command options and synopsis for help messages, and implementing the command's logic. ```javascript ctx.registerCommand({ name: 'create', fn() { const { type, name, description } = ctx.runOpts const { chalk } = ctx.helper const { appPath } = ctx.paths if (typeof name !== 'string') { return console.log(chalk.red('请输入需要创建的页面名称')) } if (type === 'page') { const Page = require('../../create/page').default const page = new Page({ pageName: name, projectDir: appPath, description, }) page.create() } }, }) ``` -------------------------------- ### Retrieve Collection Data with get() Source: https://docs.taro.zone/docs/apis/cloud/DB The `get` method retrieves data from a collection. On the mini-program side, it defaults to fetching a maximum of 20 records if `limit` is not specified. On the cloud function side, it defaults to 100 records. `skip` can be used for pagination. ```javascript const db = Taro.cloud.database() db.collection('todos').where({ _openid: 'xxx' // 填入当前用户 openid }).get().then(res => { console.log(res.data) }) ``` -------------------------------- ### Window Source: https://docs.taro.zone/docs/apis APIs for managing window size and listening for window resize events. ```APIDOC ## Taro.setWindowSize ### Description Sets the window size. This interface is only applicable to the PC platform. For detailed usage, please refer to the guide. ### Method `setWindowSize` ### Endpoint N/A (Function call) ### Parameters None ### Request Example Taro.setWindowSize({ width: 800, height: 600 }) ### Response None ``` ```APIDOC ## Taro.onWindowResize ### Description Listens for window size change events. ### Method `onWindowResize` ### Endpoint N/A (Function call) ### Parameters - **callback** (function) - The callback function to execute when the window size changes. ### Request Example Taro.onWindowResize(callbackFunction) ### Response None ``` ```APIDOC ## Taro.offWindowResize ### Description Cancels the listener for window size change events. ### Method `offWindowResize` ### Endpoint N/A (Function call) ### Parameters - **callback** (function) - The callback function to remove. ### Request Example Taro.offWindowResize(callbackFunction) ### Response None ``` -------------------------------- ### siblings Source: https://docs.taro.zone/docs/jquery-like Gets the siblings of each element in the collection. Can be filtered by a selector. ```APIDOC ## siblings ### Description Gets the siblings of each element in the collection. ### Method `siblings([selector])` ### Parameters - **selector** (string, optional) - A selector to filter the siblings. ### Returns - `collection` - A collection of the sibling elements. ``` -------------------------------- ### Using React.createElement for Views Source: https://docs.taro.zone/docs/migration Demonstrates an alternative to JSX for creating UI elements using React.createElement, importing components from '@tarojs/components'. ```javascript import React from 'react' import { View, Text } from '@tarojs/components' function C() { // 你可以选择不使用 JSX,但元素还是必须从 `@tarojs/components` 引入 const title = React.createElement(View, null, 'Numbers:') const numbers = [] for (let i = 0; i < 10; i++) { numbers.push({i}) } return ( <> {title} {numbers} ) } ``` -------------------------------- ### OnPlayCallback Source: https://docs.taro.zone/docs/apis/media/audio/InnerAudioContext Callback function triggered when the audio playback starts. ```APIDOC ## OnPlayCallback ### Description Audio playback event callback function. ### Parameters #### res - **res** (TaroGeneral.CallbackResult) - Description: Callback result object. ``` -------------------------------- ### SnapshotOption Source: https://docs.taro.zone/docs/apis/media/live/LivePlayerContext Options for taking a snapshot of the player. ```APIDOC ## SnapshotOption ### Description Options for taking a snapshot of the player. ### Parameters #### Optional Parameters - **complete** ( (res: TaroGeneral.CallbackResult) => void ) - Callback function executed when the API call ends (whether successful or failed). - **fail** ( (res: TaroGeneral.CallbackResult) => void ) - Callback function executed when the API call fails. - **success** ( (result: SnapshotSuccessCallbackResult) => void ) - Callback function executed when the API call succeeds. ``` -------------------------------- ### prev Source: https://docs.taro.zone/docs/jquery-like Gets the previous sibling of each element in the collection. Can be filtered by a selector. ```APIDOC ## prev ### Description Gets the previous sibling of each element in the collection. ### Method `prev([selector])` ### Parameters - **selector** (string, optional) - A selector to filter the previous siblings. ### Returns - `collection` - A collection of the previous sibling elements. ``` -------------------------------- ### StatOption Source: https://docs.taro.zone/docs/apis/files/FileSystemManager Options for the stat method to get file or directory status. ```APIDOC ## StatOption ### Description Options for the stat method to get file or directory status. ### Parameters #### Path Parameters - **path** (string) - Required - File/directory path #### Callback Parameters - **complete** (function) - Optional - Callback function executed when the API call ends (success or failure). - **fail** (function) - Optional - Callback function executed when the API call fails. - **success** (function) - Optional - Callback function executed when the API call succeeds. #### Other Parameters - **recursive** (boolean) - Optional - Whether to recursively get Stats information for each file in the directory. ``` -------------------------------- ### Configure Native Pages in app.config.js Source: https://docs.taro.zone/docs/hybrid Set up the routes for native pages in the app configuration file. ```javascript export default { pages: ['pages/native/native'], } ``` -------------------------------- ### Mini Program Navigation Source: https://docs.taro.zone/docs/apis APIs for opening, navigating to, and returning from other mini-programs. ```APIDOC ## Taro.openEmbeddedMiniProgram ### Description Opens a mini-program in a half-screen embedded mode. ### Method `openEmbeddedMiniProgram` ### Endpoint N/A (Function call) ### Parameters None ### Request Example Taro.openEmbeddedMiniProgram({ appId: 'your_mini_program_app_id', path: 'pages/index/index?query=1' }) ### Response None ``` ```APIDOC ## Taro.navigateToMiniProgram ### Description Opens another mini-program. ### Method `navigateToMiniProgram` ### Endpoint N/A (Function call) ### Parameters None ### Request Example Taro.navigateToMiniProgram({ appId: 'another_mini_program_app_id', path: 'pages/detail/index' }) ### Response None ``` ```APIDOC ## Taro.navigateBackMiniProgram ### Description Returns to the previous mini-program. ### Method `navigateBackMiniProgram` ### Endpoint N/A (Function call) ### Parameters None ### Request Example Taro.navigateBackMiniProgram() ### Response None ``` ```APIDOC ## Taro.exitMiniProgram ### Description Exits the current mini-program. ### Method `exitMiniProgram` ### Endpoint N/A (Function call) ### Parameters None ### Request Example Taro.exitMiniProgram() ### Response None ``` -------------------------------- ### Menu Source: https://docs.taro.zone/docs/apis API for getting information about the menu button's bounding rectangle. ```APIDOC ## Taro.getMenuButtonBoundingClientRect ### Description Retrieves the layout position information of the menu button (top-right capsule button). ### Method `getMenuButtonBoundingClientRect` ### Endpoint N/A (Function call) ### Parameters None ### Request Example const rect = Taro.getMenuButtonBoundingClientRect(); console.log(rect); ### Response - **rect** (object) - An object containing the bounding rectangle information. ``` -------------------------------- ### Configure Vuex Store in Taro Source: https://docs.taro.zone/docs/guide Set up the Vuex store and inject it into the application in the entry file for a Vue-based Taro project. ```javascript import Vue from 'vue' import Vuex from 'vuex' import './app.css' const store = new Vuex.Store({ state: { thread: {}, }, mutations: { setThread: (state, thread) => { state.thread = { ...thread } }, }, }) const App = { store, render(h) { // this.$slots.default 是将要会渲染的页面 return h('block', this.$slots.default) }, } export default App ``` -------------------------------- ### get Source: https://docs.taro.zone/docs/apis/cloud/DB Retrieves record data, or filtered records based on query conditions. ```APIDOC ## get ### Description Retrieves record data, or filtered records based on query conditions. ### Method GET (implied by operation) ### Endpoint `/collection/{collectionName}/{documentId}` (implied) ### Parameters #### Path Parameters - **collectionName** (string) - Required - The name of the collection. - **documentId** (string) - Required - The ID of the document to retrieve. #### Query Parameters - **options** (`OQ` or `RQ`) - Optional - Query options for filtering or retrieval. ### Request Example ```javascript const db = Taro.cloud.database() db.collection('todos').doc('').get().then(res => { console.log(res.data) }) ``` ### Response #### Success Response (200) - **data** (any) - The retrieved record data. #### Response Example ```json { "data": { ... } } ``` ``` -------------------------------- ### VKFrame.getCameraTexture Source: https://docs.taro.zone/docs/apis Gets the camera texture for the current frame. Currently only supports YUV textures. ```APIDOC ## VKFrame.getCameraTexture ### Description Gets the camera texture for the current frame. Currently only supports YUV textures. ### Method `VKFrame.getCameraTexture()` ```