<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          Taro3跨端跨框架原理初探

          共 28507字,需瀏覽 58分鐘

           ·

          2021-07-30 00:38

           大廠技術(shù)  堅(jiān)持周更  精選好文



          背景

          在項(xiàng)目中,我們用到了Taro3進(jìn)行跨端開發(fā),在這里分享下Taro3的一些跨端跨框架原理,也是希望能幫助自己更好的去理解Taro背后的事情,也能加速定位問題。此文章也是起到一個(gè)拋磚引玉的效果,讓自己理解的更加深入一點(diǎn)。

          過去的整體架構(gòu),它分為兩個(gè)部分,第?部分是編譯時(shí),第?部分是運(yùn)?時(shí)。編譯時(shí)會(huì)先對(duì)?戶的 React 代碼進(jìn)?編譯,轉(zhuǎn)換成各個(gè)端上的?程序都可以運(yùn)?的代碼,然后再在各個(gè)?程序端上?都配上?個(gè)對(duì)應(yīng)的運(yùn)?時(shí)框架進(jìn)?適配,最終讓這份代碼運(yùn)?在各個(gè)?程序端上?。

          Taro3之前(重編譯時(shí),輕運(yùn)行時(shí)):

          編譯時(shí)是使用 babel-parser 將 Taro 代碼解析成抽象語法樹,然后通過 babel-types 對(duì)抽象語法樹進(jìn)行一系列修改、轉(zhuǎn)換操作,最后再通過 babel-generate 生成對(duì)應(yīng)的目標(biāo)代碼。

          這樣的實(shí)現(xiàn)過程有三?缺點(diǎn):

          • JSX ?持程度不完美。Taro 對(duì) JSX 的?持是通過編譯時(shí)的適配去實(shí)現(xiàn)的,但 JSX ??常之靈活,因此還不能做到 100% ?持所有的 JSX 語法。 JSX 是一個(gè) JavaScript 的語法擴(kuò)展,它的寫法千變?nèi)f化,十分靈活。之前Taro團(tuán)隊(duì)是采用窮舉的方式對(duì) JSX 可能的寫法進(jìn)行了一一適配,這一部分工作量很大。
          • 不?持 source-map。Taro 對(duì)源代碼進(jìn)?了?系列的轉(zhuǎn)換操作之后,就不?持 source-map 了,?戶 調(diào)試、使?這個(gè)項(xiàng)?就會(huì)不?便。
          • 維護(hù)和迭代?分困難。Taro 編譯時(shí)代碼?常的復(fù)雜且離散,維護(hù)迭代都?常的困難。

          再看?下運(yùn)?時(shí)的缺陷。對(duì)于每個(gè)?程序平臺(tái),都會(huì)提供對(duì)應(yīng)的?份運(yùn)?時(shí)框架進(jìn)?適配。當(dāng)修改?些 Bug 或者新增?些特性的時(shí)候,需要同時(shí)去修改多份運(yùn)?時(shí)框架。

          總的來說,之前的Taro3.0之前有以下問題:

          Taro3之后(重運(yùn)行時(shí)):

          Taro 3 則可以大致理解為解釋型架構(gòu)(相對(duì)于 Taro 1/2 而言),主要通過在小程序端模擬實(shí)現(xiàn) DOM、BOM API 來讓前端框架直接運(yùn)行在小程序環(huán)境中,從而達(dá)到小程序和 H5 統(tǒng)一的目的,而對(duì)于生命周期、組件庫、API、路由等差異,依然可以通過定義統(tǒng)一標(biāo)準(zhǔn),各端負(fù)責(zé)各自實(shí)現(xiàn)的方式來進(jìn)行抹平。而正因?yàn)?Taro 3 的原理,在 Taro 3 中同時(shí)支持 React、Vue 等框架,甚至還支持了 jQuery,還能支持讓開發(fā)者自定義地去拓展其他框架的支持,比如 Angular,Taro 3 整體架構(gòu)如下:

          Taro 小程序:

          Taro 3 之后 ?程序端的整體架構(gòu)。?先是?戶的 React 或 Vue 的代碼會(huì)通過 CLI 進(jìn)? Webpack 打包,其次在運(yùn)?時(shí)會(huì)提供 React 和 Vue 對(duì)應(yīng)的適配器進(jìn)?適配,然后調(diào)?Taro提供的 DOM 和 BOM API, 最后把整個(gè)程序渲染到所有的?程序端上?。

          React 有點(diǎn)特殊,因?yàn)?React-DOM 包含大量瀏覽器兼容類的代碼,導(dǎo)致包太大,而這部分代碼是不需要的,因此做了一些定制和優(yōu)化。

          在 React 16+ ,React 的架構(gòu)如下:

          最上層是 React 的核心部分 react-core ,中間是 react-reconciler,其的職責(zé)是維護(hù) VirtualDOM 樹,內(nèi)部實(shí)現(xiàn)了 Diff/Fiber 算法,決定什么時(shí)候更新、以及要更新什么。

          Renderer 負(fù)責(zé)具體平臺(tái)的渲染工作,它會(huì)提供宿主組件、處理事件等等。例如 React-DOM 就是一個(gè)渲染器,負(fù)責(zé) DOM 節(jié)點(diǎn)的渲染和 DOM 事件處理。

          Taro實(shí)現(xiàn)了taro-react 包,用來連接 react-reconcilertaro-runtime 的 BOM/DOM API。是基于 react-reconciler 的小程序?qū)S?React 渲染器,連接 @tarojs/runtime的DOM 實(shí)例,相當(dāng)于小程序版的react-dom,暴露的 API 也和react-dom 保持一致。

          創(chuàng)建一個(gè)自定義渲染器只需兩步:具體的實(shí)現(xiàn)主要分為兩步:

          第一步: **實(shí)現(xiàn)宿主配置( 實(shí)現(xiàn)**react-reconcilerhostConfig**配置)這是react-reconciler要求宿主提供的一些適配器方法和配置項(xiàng)。這些配置項(xiàng)定義了如何創(chuàng)建節(jié)點(diǎn)實(shí)例、構(gòu)建節(jié)點(diǎn)樹、提交和更新等操作。即在 hostConfig 的方法中調(diào)用對(duì)應(yīng)的 Taro BOM/DOM 的 API。

          const Reconciler = require('react-reconciler');



          const HostConfig = {

            // ... 實(shí)現(xiàn)適配器方法和配置項(xiàng)

          };
          @tarojs/react reconciler.ts



          /* eslint-disable @typescript-eslint/indent */

          import Reconciler, { HostConfig } from 'react-reconciler'

          import * as scheduler from 'scheduler'

          import { TaroElement, TaroText, document } from '@tarojs/runtime'

          import { noop, EMPTY_ARR } from '@tarojs/shared'

          import { Props, updateProps } from './props'



          const {

            unstable_scheduleCallback: scheduleDeferredCallback,

            unstable_cancelCallback: cancelDeferredCallback,

            unstable_now: now

          } = scheduler



          function returnFalse ({

            return false

          }



          const hostConfig: HostConfig<

            string// Type

            Props, // Props

            TaroElement, // Container

            TaroElement, // Instance

            TaroText, // TextInstance

            TaroElement, // HydratableInstance

            TaroElement, // PublicInstance

            Record<stringany>, // HostContext

            string[], // UpdatePayload

            unknown, // ChildSet

            unknown, // TimeoutHandle

            unknown // NoTimeout

          > & {

            hideInstance (instance: TaroElement): void

            unhideInstance (instance: TaroElement, props): void

          } = {

            createInstance (type) {

              return document.createElement(type)

            },



            createTextInstance (text) {

              return document.createTextNode(text)

            },



            getPublicInstance (inst: TaroElement) {

              return inst

            },



            getRootHostContext () {

              return {}

            },



            getChildHostContext () {

              return {}

            },



            appendChild (parent, child) {

              parent.appendChild(child)

            },



            appendInitialChild (parent, child) {

              parent.appendChild(child)

            },



            appendChildToContainer (parent, child) {

              parent.appendChild(child)

            },



            removeChild (parent, child) {

              parent.removeChild(child)

            },



            removeChildFromContainer (parent, child) {

              parent.removeChild(child)

            },



            insertBefore (parent, child, refChild) {

              parent.insertBefore(child, refChild)

            },



            insertInContainerBefore (parent, child, refChild) {

              parent.insertBefore(child, refChild)

            },



            commitTextUpdate (textInst, _, newText) {

              textInst.nodeValue = newText

            },



            finalizeInitialChildren (dom, _, props) {

              updateProps(dom, {}, props)

              return false

            },



            prepareUpdate () {

              return EMPTY_ARR

            },



            commitUpdate (dom, _payload, _type, oldProps, newProps) {

              updateProps(dom, oldProps, newProps)

            },



            hideInstance (instance) {

              const style = instance.style

              style.setProperty('display''none')

            },



            unhideInstance (instance, props) {

              const styleProp = props.style

              let display = styleProp?.hasOwnProperty('display') ? styleProp.display : null

              display = display == null || typeof display === 'boolean' || display === '' ? '' : ('' + display).trim()

              // eslint-disable-next-line dot-notation

              instance.style['display'] = display

            },



            shouldSetTextContent: returnFalse,

            shouldDeprioritizeSubtree: returnFalse,

            prepareForCommit: noop,

            resetAfterCommit: noop,

            commitMount: noop,

            now,

            scheduleDeferredCallback,

            cancelDeferredCallback,

            clearTimeout: clearTimeout,

            setTimeout: setTimeout,

            noTimeout: -1,

            supportsMutation: true,

            supportsPersistence: false,

            isPrimaryRenderer: true,

            supportsHydration: false

          }



          export const TaroReconciler = Reconciler(hostConfig)

          第二步:實(shí)現(xiàn)渲染函數(shù),類似于ReactDOM.render() 方法??梢钥闯墒莿?chuàng)建 Taro DOM Tree 容器的方法。

          // 創(chuàng)建Reconciler實(shí)例, 并將HostConfig傳遞給Reconciler

          const MyRenderer = Reconciler(HostConfig);



          /**

           * 假設(shè)和ReactDOM一樣,接收三個(gè)參數(shù)

           * render(<MyComponent />, container, () => console.log('rendered'))

           */


          export function render(element, container, callback{

            // 創(chuàng)建根容器

            if (!container._rootContainer) {

              container._rootContainer = ReactReconcilerInst.createContainer(container, false);

            }



            // 更新根容器

            return ReactReconcilerInst.updateContainer(element, container._rootContainer, null, callback);

          }

          經(jīng)過上面的步驟,React 代碼實(shí)際上就可以在小程序的運(yùn)行時(shí)正常運(yùn)行了,并且會(huì)生成 Taro DOM Tree。那么偌大的 Taro DOM Tree 怎樣更新到頁面呢?

          因?yàn)?程序并沒有提供動(dòng)態(tài)創(chuàng)建節(jié)點(diǎn)的能?,需要考慮如何使?相對(duì)靜態(tài)的 wxml 來渲染相對(duì)動(dòng)態(tài)的 Taro DOM 樹。Taro使?了模板拼接的?式,根據(jù)運(yùn)?時(shí)提供的 DOM 樹數(shù)據(jù)結(jié)構(gòu),各 templates 遞歸地 相互引?,最終可以渲染出對(duì)應(yīng)的動(dòng)態(tài) DOM 樹。

          首先,將小程序的所有組件挨個(gè)進(jìn)行模版化處理,從而得到小程序組件對(duì)應(yīng)的模版。如下圖就是小程序的 view 組件模版經(jīng)過模版化處理后的樣子。?先需要在 template ??寫?個(gè) view,把它所有的屬性全部列出來(把所有的屬性都列出來是因?yàn)?程序??不能去動(dòng)態(tài)地添加屬性)。

          接下來是遍歷渲染所有?節(jié)點(diǎn),基于組件的 template,動(dòng)態(tài) “遞歸” 渲染整棵樹。

          具體流程為先去遍歷 Taro DOM Tree 根節(jié)點(diǎn)的子元素,再根據(jù)每個(gè)子元素的類型選擇對(duì)應(yīng)的模板來渲染子元素,然后在每個(gè)模板中我們又會(huì)去遍歷當(dāng)前元素的子元素,以此把整個(gè)節(jié)點(diǎn)樹遞歸遍歷出來。

          Taro H5:

          Taro 這邊遵循的是以微信小程序?yàn)橹?,其他小程序?yàn)檩o的組件與 API 規(guī)范。 但瀏覽器并沒有小程序規(guī)范的組件與 API 可供使用,我們不能在瀏覽器上使用小程序的 view 組件和 getSystemInfo API。因此Taro在 H5 端實(shí)現(xiàn)一套基于小程序規(guī)范的組件庫和 API 庫。

          再來看?下 H5 端的架構(gòu),同樣的也是需要把?戶的 React 或者 Vue 代碼通過 Webpack 進(jìn)?打包。然后在運(yùn)?時(shí)做了三件事情:第?件事情是實(shí)現(xiàn)了?個(gè)組件庫,組件庫需要同時(shí)給到 React 、Vue 甚?更加多的?些框架去使?,Taro使?了 Stencil 去實(shí)現(xiàn)了?個(gè)基于 WebComponents 且遵循微信?程序規(guī)范的組件庫,第?、三件事是實(shí)現(xiàn)了?個(gè)?程序規(guī)范的 API 和路由機(jī)制,最終就可以把整個(gè)程序給運(yùn)?在瀏覽器上?。下面,我們主要關(guān)注實(shí)現(xiàn)組件庫。

          實(shí)現(xiàn)組件庫:

          最先容易想到的是使用 Vue 再開發(fā)一套組件庫,這樣最為穩(wěn)妥,工作量也沒有特別大。

          但考慮到以下兩點(diǎn),官方遂放棄了此思路:

          1. 組件庫的可維護(hù)性和拓展性不足。每當(dāng)有問題需要修復(fù)或新功能需要添加,需要分別對(duì) React 和 Vue 版本的組件庫進(jìn)行改造。
          2. Taro Next 的目標(biāo)是支持使用任意框架開發(fā)多端應(yīng)用。倘若將來支持使用 Angular 等框架進(jìn)行開發(fā),那么需要再開發(fā)對(duì)應(yīng)支持 Angular 等框架的組件庫。

          那么是否存在著一種方案,使得只用一份代碼構(gòu)建的組件庫能兼容所有的 web 開發(fā)框架呢?

          Taro的選擇是 Web Components

          Web Components

          Web Components 由一系列的技術(shù)規(guī)范所組成,它讓開發(fā)者可以開發(fā)出瀏覽器原生支持的組件。允許你創(chuàng)建可重用的定制元素(它們的功能封裝在你的代碼之外)并且在你的web應(yīng)用中使用它們。

          Web Components— 它由三項(xiàng)主要技術(shù)組成,它們可以一起使用來創(chuàng)建封裝功能的定制元素,可以在你喜歡的任何地方重用,不必?fù)?dān)心代碼沖突。

          • Custom elements(自定義元素):一組JavaScript API,允許您定義custom elements及其行為,然后可以在您的用戶界面中按照需要使用它們。簡單來說,就是讓開發(fā)者可以自定義帶有特定行為的 HTML 標(biāo)簽。

          • Shadow DOM(影子DOM):一組JavaScript API,用于將封裝的“影子”DOM樹附加到元素(與主文檔DOM分開呈現(xiàn))并控制其關(guān)聯(lián)的功能。通過這種方式,您可以保持元素的功能私有,這樣它們就可以被腳本化和樣式化,而不用擔(dān)心與文檔的其他部分發(fā)生沖突。簡單來說,就是對(duì)標(biāo)簽內(nèi)的結(jié)構(gòu)和樣式進(jìn)行一層包裝。

          • HTML templates(HTML模板):  <template><slot> 元素使您可以編寫不在呈現(xiàn)頁面中顯示的標(biāo)記模板。然后它們可以作為自定義元素結(jié)構(gòu)的基礎(chǔ)被多次重用。

          實(shí)現(xiàn)web component的基本方法通常如下所示:

          1. 創(chuàng)建一個(gè)類或函數(shù)來指定web組件的功能。
          2. 使用  CustomElementRegistry.define() 方法注冊(cè)您的新自定義元素 ,并向其傳遞要定義的元素名稱、指定元素功能的類、以及可選的其所繼承自的元素。
          3. 如果需要的話,使用Element.attachShadow() 方法將一個(gè)shadow DOM附加到自定義元素上。使用通常的DOM方法向shadow DOM中添加子元素、事件監(jiān)聽器等等。
          4. 如果需要的話,使用<template> 和 <slot> 定義一個(gè)HTML模板。再次使用常規(guī)DOM方法克隆模板并將其附加到您的shadow DOM中。
          5. 在頁面任何您喜歡的位置使用自定義元素,就像使用常規(guī)HTML元素那樣。
          示例

          定義模板:

          <template id="template">

            <h1>Hello World!</h1>

          </
          template>

          構(gòu)造 Custom Element:

          class App extends HTMLElement {

            constructor () {

              super(...arguments)



              // 開啟 Shadow DOM

              const shadowRoot = this.attachShadow({ mode: 'open' })



              // 復(fù)用 <template> 定義好的結(jié)構(gòu)

              const template = document.querySelector('#template')

              const node = template.content.cloneNode(true)

              shadowRoot.appendChild(node)

            }

          }

          window.customElements.define('my-app', App)

          使用:

          <my-app></my-app>

          使用原生語法去編寫 Web Components 相當(dāng)繁瑣,因此需要一個(gè)框架幫助我們提高開發(fā)效率和開發(fā)體驗(yàn)。業(yè)界已經(jīng)有很多成熟的 Web Components 框架,Taro選擇的是Stencil,Stencil 是一個(gè)可以生成 Web Components 的編譯器。它糅合了業(yè)界前端框架的一些優(yōu)秀概念,如支持 Typescript、JSX、虛擬 DOM 等。

          創(chuàng)建 Stencil Component:

          import { Component, Prop, State, h } from '@stencil/core'



          @Component({

            tag: 'my-component'

          })

          export class MyComponent {

            @Prop() first = ''

            @State() last = 'JS'



            componentDidLoad () {

              console.log('load')

            }



            render () {

              return (

                <div>

                  Hello, my name is {this.first} {this.last}

                </div>

              )

            }

          }

          使用組件:

          <my-component first='Taro' />

          在 React 中使用 Stencil

          Custom Elements Everywhere[1] 上羅列出業(yè)界前端框架對(duì) Web Components 的兼容問題及相關(guān) issues。在React文檔中,也略微提到過在在 React 中使用 Web Components的注意事項(xiàng) https://zh-hans.reactjs.org/docs/web-components.html#using-web-components-in-react

          在Custom Elements Everywhere 上可以看到,React 對(duì) Web Components 的兼容問題。

          翻譯過來,就是說。

          1. React 使用 setAttribute 的形式給 Web Components 傳遞參數(shù)。當(dāng)參數(shù)為原始類型時(shí)是可以運(yùn)行的,但是如果參數(shù)為對(duì)象或數(shù)組時(shí),由于 HTML 元素的 attribute 值只能為字符串或 null,最終給 WebComponents 設(shè)置的 attribute 會(huì)是 attr="[object Object]"。

          attribute和property的區(qū)別:https://stackoverflow.com/questions/6003819/what-is-the-difference-between-properties-and-attributes-in-html#answer-6004028,不展開說了。

          1. 因?yàn)?React 有一套自己實(shí)現(xiàn)的合成事件系統(tǒng),所以它不能監(jiān)聽到 Web Components 發(fā)出的自定義事件。

          reactify-wc.js

          實(shí)際上,這個(gè)高階組件的實(shí)現(xiàn)是根據(jù)開源庫reactify-wc修改的一個(gè)版本,reactify-wc是一個(gè)銜接 WebComponent 和 React 的庫,目的是為了在React 中能夠使用 WebComponent。這個(gè)修改的庫就是為了解決上述所說的問題。

          props

          Taro的處理,采用 DOM Property 的方法傳參。把 Web Components 包裝一層高階組件,把高階組件上的 props 設(shè)置為 Web Components 的 property。

          const reactifyWebComponent = WC => {

          return class Index extends React.Component {

          ref = React.createRef()

          update (prevProps) {

          this.clearEventHandlers()

          if (!this.ref.current) return



          Object.keys(prevProps || {}).forEach((key) => {

          if (key !== 'children' && key !== 'key' && !(key in this.props)) {

          updateProp(this, WC, key, prevProps, this.props)

          }

          })



          Object.keys(this.props).forEach((key) => {

          updateProp(this, WC, key, prevProps, this.props)

          })

          }



          componentDidUpdate () {

          this.update()

          }



          componentDidMount () {

          this.update()

          }



          render () {

          const { children, dangerouslySetInnerHTML } = this.props

          return React.createElement(WC, {

          ref: this.ref,

          dangerouslySetInnerHTML

          }, children)

          }
          Event

          因?yàn)?React 有一套自己實(shí)現(xiàn)的合成事件系統(tǒng),所以它不能監(jiān)聽到 Web Components 發(fā)出的自定義事件。以下 Web Component 的 onLongPress 回調(diào)不會(huì)被觸發(fā):

          <my-view onLongPress={onLongPress}>view</my-view>

          通過 ref 取得 Web Component 元素,手動(dòng) addEventListener 綁定事件。改造上述的高階組件:

          const reactifyWebComponent = WC => {

            return class Index extends React.Component {

              ref = React.createRef()

              eventHandlers = []



              update () {

                this.clearEventHandlers()



                Object.entries(this.props).forEach(([prop, val]) => {

                  if (typeof val === 'function' && prop.match(/^on[A-Z]/)) {

                    const event = prop.substr(2).toLowerCase()

                    this.eventHandlers.push([event, val])

                    return this.ref.current.addEventListener(event, val)

                  }



                  ...

                })

              }



              clearEventHandlers () {

                this.eventHandlers.forEach(([event, handler]) => {

                  this.ref.current.removeEventListener(event, handler)

                })

                this.eventHandlers = []

              }



              componentWillUnmount () {

                this.clearEventHandlers()

              }



              ...

            }

          }
          ref

          為了解決 Props 和 Events 的問題,引入了高階組件。那么當(dāng)開發(fā)者向高階組件傳入 ref 時(shí),獲取到的其實(shí)是高階組件,但我們希望開發(fā)者能獲取到對(duì)應(yīng)的 Web Component。

          domRef 會(huì)獲取到 MyComponent,而不是 <my-component></my-component>

          <MyComponent ref={domRef} />

          使用 forwardRef[2] 傳遞 ref。改造上述的高階組件為 forwardRef 形式:

          const reactifyWebComponent = WC => {

            class Index extends React.Component {

              ...



              render () {

                const { children, forwardRef } = this.props

                return React.createElement(WC, {

                  ref: forwardRef

                }, children)

              }

            }

            return React.forwardRef((props, ref) => (

              React.createElement(Index, { ...props, forwardRef: ref })

            ))

          }
          className

          在 Stencil 里我們可以使用 Host 組件為 host element 添加類名。

          import { Component, Host, h } from '@stencil/core';



          @Component({

            tag: 'todo-list'

          })

          export class TodoList {

            render () {

              return (

                <Host class='todo-list'>

                  <div>todo</div>

                </
          Host>

              )

            }

          }

          然后在使用 <todo-list> 元素時(shí)會(huì)展示我們內(nèi)置的類名 “todo-list” 和 Stencil 自動(dòng)加入的類名 “hydrated”:

          關(guān)于類名 “hydrated”:

          Stencil 會(huì)為所有 Web Components 加上 visibility: hidden; 的樣式。然后在各 Web Component 初始化完成后加入類名 “hydrated”,將 visibility 改為 inherit。如果 “hydrated” 被抹除掉,Web Components 將不可見。

          為了不要覆蓋 wc 中 host 內(nèi)置的 class 和 stencil 加入的 class,對(duì)對(duì)內(nèi)置 class 進(jìn)行合并。

          function getClassName (wc, prevProps, props{

            const classList = Array.from(wc.classList)

            const oldClassNames = (prevProps.className || prevProps.class || '').split(' ')

            let incomingClassNames = (props.className || props.class || '').split(' ')

            let finalClassNames = []



            classList.forEach(classname => {

              if (incomingClassNames.indexOf(classname) > -1) {

                finalClassNames.push(classname)

                incomingClassNames = incomingClassNames.filter(name => name !== classname)

              } else if (oldClassNames.indexOf(classname) === -1) {

                finalClassNames.push(classname)

              }

            })



            finalClassNames = [...finalClassNames, ...incomingClassNames]



            return finalClassNames.join(' ')

          }

          到這里,我們的reactify-wc就打造好了。我們不要忘了,Stencil是幫我們寫web components的,reactify-wc 目的是為了在React 中能夠使用 WebComponent。如下包裝后,我們就能直接在react里面用View、Text等組件了

          //packages/taro-components/h5



          import reactifyWc from './utils/reactify-wc'

          import ReactInput from './components/input'



          export const View = reactifyWc('taro-view-core')

          export const Icon = reactifyWc('taro-icon-core')

          export const Progress = reactifyWc('taro-progress-core')

          export const RichText = reactifyWc('taro-rich-text-core')

          export const Text = reactifyWc('taro-text-core')

          export const Button = reactifyWc('taro-button-core')

          export const Checkbox = reactifyWc('taro-checkbox-core')

          export const CheckboxGroup = reactifyWc('taro-checkbox-group-core')

          export const Editor = reactifyWc('taro-editor-core')

          export const Form = reactifyWc('taro-form-core')

          export const Input = ReactInput

          export const Label = reactifyWc('taro-label-core')

          export const Picker = reactifyWc('taro-picker-core')

          export const PickerView = reactifyWc('taro-picker-view-core')

          export const PickerViewColumn = reactifyWc('taro-picker-view-column-core')

          export const Radio = reactifyWc('taro-radio-core')

          export const RadioGroup = reactifyWc('taro-radio-group-core')

          export const Slider = reactifyWc('taro-slider-core')

          export const Switch = reactifyWc('taro-switch-core')

          export const CoverImage = reactifyWc('taro-cover-image-core')

          export const Textarea = reactifyWc('taro-textarea-core')

          export const CoverView = reactifyWc('taro-cover-view-core')

          export const MovableArea = reactifyWc('taro-movable-area-core')

          export const MovableView = reactifyWc('taro-movable-view-core')

          export const ScrollView = reactifyWc('taro-scroll-view-core')

          export const Swiper = reactifyWc('taro-swiper-core')

          export const SwiperItem = reactifyWc('taro-swiper-item-core')

          export const FunctionalPageNavigator = reactifyWc('taro-functional-page-navigator-core')

          export const Navigator = reactifyWc('taro-navigator-core')

          export const Audio = reactifyWc('taro-audio-core')

          export const Camera = reactifyWc('taro-camera-core')

          export const Image = reactifyWc('taro-image-core')

          export const LivePlayer = reactifyWc('taro-live-player-core')

          export const Video = reactifyWc('taro-video-core')

          export const Map = reactifyWc('taro-map-core')

          export const Canvas = reactifyWc('taro-canvas-core')

          export const Ad = reactifyWc('taro-ad-core')

          export const OfficialAccount = reactifyWc('taro-official-account-core')

          export const OpenData = reactifyWc('taro-open-data-core')

          export const WebView = reactifyWc('taro-web-view-core')

          export const NavigationBar = reactifyWc('taro-navigation-bar-core')

          export const Block = reactifyWc('taro-block-core')

          export const CustomWrapper = reactifyWc('taro-custom-wrapper-core')
          //packages/taro-components/src/components/view/view.tsx

          //拿View組件舉個(gè)例子



          // eslint-disable-next-line @typescript-eslint/no-unused-vars

          import { Component, Prop, h, ComponentInterface, Host, Listen, State, Event, EventEmitter } from '@stencil/core'

          import classNames from 'classnames'



          @Component({

            tag: 'taro-view-core',

            styleUrl: './style/index.scss'

          })

          export class View implements ComponentInterface {

            @Prop() hoverClass: string

            @Prop() hoverStartTime = 50

            @Prop() hoverStayTime = 400

            @State() hover = false

            @State() touch = false



            @Event({

              eventName: 'longpress'

            }) onLongPress: EventEmitter



            private timeoutEvent: NodeJS.Timeout

            private startTime = 0



            @Listen('touchstart')

            onTouchStart () {

              if (this.hoverClass) {

                this.touch = true

                setTimeout(() => {

                  if (this.touch) {

                    this.hover = true

                  }

                }, this.hoverStartTime)

              }



              this.timeoutEvent = setTimeout(() => {

                this.onLongPress.emit()

              }, 350)

              this.startTime = Date.now()

            }



            @Listen('touchmove')

            onTouchMove () {

              clearTimeout(this.timeoutEvent)

            }



            @Listen('touchend')

            onTouchEnd () {

              const spanTime = Date.now() - this.startTime

              if (spanTime < 350) {

                clearTimeout(this.timeoutEvent)

              }

              if (this.hoverClass) {

                this.touch = false

                setTimeout(() => {

                  if (!this.touch) {

                    this.hover = false

                  }

                }, this.hoverStayTime)

              }

            }



            render () {

              const cls = classNames({

                [`${this.hoverClass}`]: this.hover

              })

              return (

                <Host class={cls}>

                  <slot></slot>

                </
          Host>

              )

            }

          }

          至此,組件庫就實(shí)現(xiàn)好了。

          Taro 3 部分使用的 NPM 包名及其具體作用。

          NPM 包描述
          babel-preset-taro[3]給 Taro 項(xiàng)目使用的 babel preset
          @tarojs/taro[4]暴露給應(yīng)用開發(fā)者的 Taro 核心 API
          @tarojs/shared[5]Taro 內(nèi)部使用的 utils
          @tarojs/api[6]暴露給 @tarojs/taro 的所有端的公有 API
          @tarojs/taro-h5[7]暴露給 @tarojs/taro 的 H5 端 API
          @tarojs/router[8]Taro H5 路由
          @tarojs/react[9]基于 react-reconciler 的小程序?qū)S?React 渲染器
          @tarojs/cli[10]Taro 開發(fā)工具
          @tarojs/extend[11]Taro 擴(kuò)展,包含 jQuery API 等
          @tarojs/helper[12]內(nèi)部給 CLI 和 runner 使用輔助方法集
          @tarojs/service[13]Taro 插件化內(nèi)核
          @tarojs/taro-loader[14]露給 @tarojs/mini-runner 和 @tarojs/webpack-runner 使用的 Webpack loader
          @tarojs/runner-utils[15]暴露給 @tarojs/mini-runner 和 @tarojs/webpack-runner 的公用工具函數(shù)
          @tarojs/webpack-runner[16]Taro H5 端 Webpack 打包編譯工具
          @tarojs/mini-runner[17]Taro 小程序 端 Webpack 打包編譯工具
          @tarojs/components[18]Taro 標(biāo)準(zhǔn)組件庫,H5 版
          @tarojs/taroize[19]Taro 小程序反向編譯器
          @tarojs/with-weapp[20]反向轉(zhuǎn)換的運(yùn)行時(shí)適配器
          eslint-config-taro[21]Taro ESLint 規(guī)則
          eslint-plugin-taro[22]Taro ESLint 插件

          總結(jié)

          Taro 3重構(gòu)是為了解決架構(gòu)問題,還有提供多框架的?持。從之前的重編譯時(shí),到現(xiàn)在的重運(yùn)行時(shí)。

          同等條件下,編譯時(shí)做的工作越多,也就意味著運(yùn)行時(shí)做的工作越少,性能會(huì)更好。從長遠(yuǎn)來看,計(jì)算機(jī)硬件的性能越來越冗余,如果在犧牲一點(diǎn)可以容忍的性能的情況下?lián)Q來整個(gè)框架更大的靈活性和更好的適配性,并且能夠極大的提升開發(fā)體驗(yàn)。

          參考

          1. https://github.com/NervJS/taro
          2. https://mp.weixin.qq.com/s?__biz=MzU3NDkzMTI3MA==&mid=2247483770&idx=1&sn=ba2cdea5256e1c4e7bb513aa4c837834
          3. https://www.yuque.com/zaotalk/posts/cz8knq#HUlMM
          4. https://juejin.cn/post/6868099130720256007#heading-0
          5. https://developer.mozilla.org/zh-CN/docs/Web/Web_Components
          6. https://custom-elements-everywhere.com/
          7. https://zhuanlan.zhihu.com/p/83324871

          參考資料

          [1]

          Custom Elements Everywhere: https://custom-elements-everywhere.com/

          [2]

          forwardRef: https://reactjs.org/docs/forwarding-refs.html#forwarding-refs-to-dom-components

          [3]

          babel-preset-taro: https://www.npmjs.com/package/babel-preset-taro

          [4]

          @tarojs/taro: https://www.npmjs.com/package/@tarojs/taro

          [5]

          @tarojs/shared: https://www.npmjs.com/package/@tarojs/shared

          [6]

          @tarojs/api: https://www.npmjs.com/package/@tarojs/api

          [7]

          @tarojs/taro-h5: https://www.npmjs.com/package/@tarojs/taro-h5

          [8]

          @tarojs/router: https://www.npmjs.com/package/@tarojs/router

          [9]

          @tarojs/react: https://www.npmjs.com/package/@tarojs/react

          [10]

          @tarojs/cli: https://www.npmjs.com/package/@tarojs/cli

          [11]

          @tarojs/extend: https://www.npmjs.com/package/@tarojs/extend

          [12]

          @tarojs/helper: https://www.npmjs.com/package/@tarojs/helper

          [13]

          @tarojs/service: https://www.npmjs.com/package/@tarojs/service

          [14]

          @tarojs/taro-loader: https://www.npmjs.com/package/@tarojs/taro-loader

          [15]

          @tarojs/runner-utils: https://www.npmjs.com/package/@tarojs/runner-utils

          [16]

          @tarojs/webpack-runner: https://www.npmjs.com/package/@tarojs/webpack-runner

          [17]

          @tarojs/mini-runner: https://www.npmjs.com/package/@tarojs/mini-runner

          [18]

          @tarojs/components: https://www.npmjs.com/package/@tarojs/components

          [19]

          @tarojs/taroize: https://www.npmjs.com/package/@tarojs/taroize

          [20]

          @tarojs/with-weapp: https://www.npmjs.com/package/@tarojs/with-weapp

          [21]

          eslint-config-taro: https://www.npmjs.com/package/eslint-config-taro

          [22]

          eslint-plugin-taro: https://www.npmjs.com/package/eslint-plugin-taro

          ?? 謝謝支持

          以上便是本次分享的全部內(nèi)容,希望對(duì)你有所幫助^_^

          喜歡的話別忘了 分享、點(diǎn)贊、收藏 三連哦~。

          歡迎關(guān)注公眾號(hào) 前端Sharing 收貨大廠一手好文章~

          瀏覽 91
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評(píng)論
          圖片
          表情
          推薦
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  播播网色播播 | 欧美污视频网站 | 亚洲在线无码播放 | 黄色视频在线观看地址 | 久久久久无码精品 |