跳至主要内容

Taro 中通过动态插入节点实现 API Toast

 原文链接

什么是动态插入节点

web端加入我们需要实现一个可以通过API调用的 Toast,我们可以这样实现:

const Toast = (props)=>{
    return <div>{props.msg}</div>
}
const showToast = (options)=>{
    const div = document.createElement('div');
    div.setAttribute('id', 'toast');
    document.body.appendChild(div);
    ReactDOM.render(React.createElement(Toast, options), div);
}
const hideTosat = ()=>{
    if(!document.getElementById("toast")) return;
    document.getElementById("toast").remove()
}

我们依赖的就是浏览器Document对象,提供的可以操作dom的方法。但是我们都知道小程序没有提供Document对象,那么我们该如何去实现类似的功能呢?

taro中动态插入节点的实现

import React from 'react';
import Taro from '@tarojs/taro';
import { render, unmountComponentAtNode } from '@tarojs/react';
import { document, TaroRootElement } from '@tarojs/runtime';
import { View } from '@tarojs/components';

const Demo = ({ msg }) => {
return <View style={{ position: 'fixed', top: 0 }}>{msg}</View>;
};

export const createNotification = (msg: string) => {
    const view = document.createElement('view');
    const currentPages = Taro.getCurrentPages();
    const currentPage = currentPages[currentPages.length - 1];// 获取当前页面对象
    const path = currentPage.$taroPath;
    const pageElement = document.getElementById<TaroRootElement>(path);
    render(<Demo msg={msg} />, view);
    pageElement?.appendChild(view);
};


export const destroyNotification = (node) => {
    const currentPages = Taro.getCurrentPages();
    const currentPage = currentPages[currentPages.length - 1];
    const path = currentPage.$taroPath;
    const pageElement = document.getElementById<TaroRootElement>(path);
    unmountComponentAtNode(node);
    pageElement?.remove(node);
};

为什么可以这样实现?

引文

在使用 React 时,我们会引用 react 和 react-dom 。而在 react-dom 中依赖 react-reconciler

那么三者各自负责什么部分,又有什么联系呢?推荐阅读 react-dom 与 react 之间的关系

总结来说:react 负责描述特性,提供React APIreact-dom 负责实现特性操作真实的 dom 节点。

taro 中的 react-dom

我们知道 web端 有 react-dom, 移动端 有 react-native。那么 taro 又是通过什么操作小程序 dom 的呢? 答案是 @tarojs/react,与 web端、移动端一样 @tarojs/react依赖 react-reconciler

但我们都知道小程序并没有提供像 web端 一样的操作 dom 的方法。那么@tarojs/react又是怎么实现对小程序 dom 的操作的呢? 答案是@tarojs/runtime

源码

TaroDocument

就是上述 demo 中所引入的 document 对象

export class TaroDocument extends TaroElement {
    // ...
}
TaroElement
export class TaroElement extends TaroNode {
    // ...
}
TaroNode

通过层层继承关系最终 document.appendChild()方法调用的是 TaroNode 类中的 appendChild。而TaroNode 类中的 appendChild方法通过层层逻辑调用最终调用了this._root?.enqueueUpdate(payload)即根节点中的enqueueUpdate方法,也就是TaroRootElement类中的enqueueUpdate方法

export class TaroNode extends TaroEventTarget {

  /**
   * @doc https://developer.mozilla.org/zh-CN/docs/Web/API/Node/appendChild
   * @scenario
   * [A,B,C]
   *   1. append C, C has no parent
   *   2. append C, C has the same parent of B
   *   3. append C, C has the different parent of B
   */
  public appendChild (newChild: TaroNode) {
    return this.insertBefore(newChild)
  }
  
    /**
   * @doc https://developer.mozilla.org/zh-CN/docs/Web/API/Node/insertBefore
   * @scenario
   * [A,B,C]
   *   1. insert D before C, D has no parent
   *   2. insert D before C, D has the same parent of C
   *   3. insert D before C, D has the different parent of C
   */
  public insertBefore<T extends TaroNode> (newChild: T, refChild?: TaroNode | null, isReplace?: boolean): T {
  
     // ... 省略部分逻辑 ...
  
     // Serialization
    if (this._root) {
      if (!refChild) {
        // appendChild
        const isOnlyChild = this.childNodes.length === 1
        if (isOnlyChild) {
          this.updateChildNodes() // 更新节点
        } else {
          this.enqueueUpdate({
            path: newChild._path,
            value: this.hydrate(newChild)
          }) // 更新节点
        }
      } else if (isReplace) {
        // replaceChild
        this.enqueueUpdate({
          path: newChild._path,
          value: this.hydrate(newChild)
        }) // 更新节点
      } else {
        // insertBefore
        this.updateChildNodes() // 更新节点
      }
    }
    
    // ... 省略部分逻辑 ...
  }
  
  private updateChildNodes (isClean?: boolean) {
    const cleanChildNodes = () => []
    const rerenderChildNodes = () => {
      const childNodes = this.childNodes.filter(node => !isComment(node))
      return childNodes.map(hydrate)
    }

    this.enqueueUpdate({
      path: `${this._path}.${CHILDNODES}`,
      value: isClean ? cleanChildNodes : rerenderChildNodes
    }) // 更新节点
  }
  
  // ... 省略部分逻辑 ...
  
  public enqueueUpdate (payload: UpdatePayload) {
    this._root?.enqueueUpdate(payload)
  }
  
  public get _root (): TaroRootElement | null {
    return this.parentNode?._root || null
  }

}
TaroRootElement

通过层层调用 enqueueUpdate 方法最终调用 performUpdate 方法。而 performUpdate 方法的核心是 ctx.setData() 是不是感觉和微信页面的 setData 很像?其实不止是像,他调用的就是微信的setData

export class TaroRootElement extends TaroElement {
  
  // ... 省略部分逻辑 ...
  
  public ctx: null | MpInstance = null
  
  public get _root (): TaroRootElement {
    return this
  }

  public enqueueUpdate (payload: UpdatePayload): void {
    this.updatePayloads.push(payload)

    if (!this.pendingUpdate && this.ctx) {
      this.performUpdate()
    }
  }
  
  public performUpdate (initRender = false, prerender?: Func) {
    this.pendingUpdate = true

    const ctx = this.ctx!
    
    // ... 省略部分逻辑 ...
     
    // custom-wrapper setData
    if (customWrpperCount) {
      customWrapperMap.forEach((data, ctx) => {
        if (process.env.NODE_ENV !== 'production' && options.debug) {
          // eslint-disable-next-line no-console
          console.log('custom wrapper setData: ', data)
        }
        ctx.setData(data, cb)
      })
    }

    // page setData
    if (isNeedNormalUpdate) {
      if (process.env.NODE_ENV !== 'production' && options.debug) {
        // eslint-disable-next-line no-console
        console.log('page setData:', normalUpdate)
      }
      ctx.setData(normalUpdate, cb)
    }    
  }
  
  // ... 省略部分逻辑 ...
}
createPageConfig

仔细阅读以下源码可知

  • 获取页面根节点的方法为document.getElementById<TaroRootElement>($taroPath)
  • TaroRootElement 中 ctx 的值为页面this,所以TaroRootElement 中 ctx.setState其实就是微信页面的this.setState
export function createPageConfig (component: any, pageName?: string, data?: Record<string, unknown>, pageConfig?: PageConfig) {
  // 小程序 Page 构造器是一个傲娇小公主,不能把复杂的对象挂载到参数上
  const id = pageName ?? `taro_page_${pageId()}`
  
  // ... 省略部分逻辑 ...
  
  const config: PageInstance = {
      [ONLOAD] (this: MpInstance, options: Readonly<Record<string, unknown>> = {}, cb?: Func) {
      hasLoaded = new Promise(resolve => { loadResolver = resolve })

      perf.start(PAGE_INIT)

      Current.page = this as any
      this.config = pageConfig || {}

      // this.$taroPath 是页面唯一标识
      const uniqueOptions = Object.assign({}, options, { $taroTimestamp: Date.now() })
      const $taroPath = this.$taroPath = getPath(id, uniqueOptions)
      if (process.env.TARO_ENV === 'h5') {
        config.path = $taroPath
      }
      // this.$taroParams 作为暴露给开发者的页面参数对象,可以被随意修改
      if (this.$taroParams == null) {
        this.$taroParams = uniqueOptions
      }

      setCurrentRouter(this)

      const mount = () => {
        Current.app!.mount!(component, $taroPath, () => {
          pageElement = env.document.getElementById<TaroRootElement>($taroPath) // 在这里我们知道页面根节点的查找方式

          ensure(pageElement !== null, '没有找到页面实例。')
          safeExecute($taroPath, ON_LOAD, this.$taroParams)
          loadResolver()
          if (process.env.TARO_ENV !== 'h5') {
            pageElement.ctx = this // 在这里为 TaroRootElement 注入 ctx 的值为页面 this
            pageElement.performUpdate(true, cb)
          } else {
            isFunction(cb) && cb()
          }
        })
      }
      if (unmounting) {
        prepareMountList.push(mount)
      } else {
        mount()
      }
    },
    // ... 省略部分逻辑 ...
  }
  // ... 省略部分逻辑 ...
}

总结

<import src="../../base.wxml"/>
<template is="taro_tmpl" data="{{root:root}}" />

最后我们可以看看我们的小程序编译结果,其中有一个base.wxml是每一个页面的index.wxml依赖的,而每一个页面的index.wxml都和上面列出的代码一致。所以taro渲染的真相就是通过对小程序的data进行循环得出而dom更新的真相就是setState。那么我们同样可以通过@tarojs/react@tarojs/runtime动态操作小程序dom与web端的体验一致。

评论

此博客中的热门博文

Resolving errSecInternalComponent errors during code signing

原文链接 One code signing issue I commonly see, both here on DevForums and in my Day Job™ with DTS, is that the codesign command fails with errSecInternalComponent. This issue crops up in a wide variety of circumstances and the correct fix depends on the specific problem. This post is my attempt to clarify the potential causes of this error and help folks resolve it. If you have any questions or comments about this, please start a new thread, tagging it with Code Signing so that I see it. Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com" Resolving errSecInternalComponent errors during code signing In some circumstances the codesign command might fail with the error errSecInternalComponent. For example: % codesign -s "Apple Development" "MyTrue" MyTrue: errSecInternalComponent This typically affects folks who are signing code in a nonstandard environm...

iOS:检测使用VPN或Proxy

参考链接: https://www.jianshu.com/p/c3b950dbf86a https://gist.github.com/PramodJoshi/4faad4c91f7dcb4eb9b06be8390c01db http://noodlecode.net/2018/04/check-if-ios-app-is-connected-to-vpn 第一种方法 需要导入框架CFNetwork 然后,这个方法是mrc的:需要添加-fno-objc-arc的flag 代码如下: + ( BOOL )getProxyStatus { NSDictionary *proxySettings = NSMakeCollectable ([( NSDictionary *) CFNetworkCopySystemProxySettings () autorelease]); NSArray *proxies = NSMakeCollectable ([( NSArray *) CFNetworkCopyProxiesForURL (( CFURLRef )[ NSURL URLWithString: @"http://www.google.com" ], ( CFDictionaryRef )proxySettings) autorelease]); NSDictionary *settings = [proxies objectAtIndex: 0 ]; NSLog ( @"host=%@" , [settings objectForKey:( NSString *)kCFProxyHostNameKey]); NSLog ( @"port=%@" , [settings objectForKey:( NSString *)kCFProxyPortNumberKey]); NSLog ( @"type=%@" , [settings objectForKey:( NSString *)kCFProxyTypeKey]); if ([[settings object...

去广告DNS设置,国内ADGuard DNS方案,手机电脑iOS去广告,保护隐私

 原文链接 之前分享过使用mac系统搭建adguard home,这几个月用下来零零散散基本上也被弃用了。主要原因是因为需要保持电脑一直开机。但是我的电脑是笔记本,存在移动各个地域的情况,也就是说只能够屏蔽电脑自身,对于手机而言不太现实。今天偶然发现dnspod推出了高级版的公共解析。dnspod背靠腾讯云,肯定是合法合规的公共解析服务,这个高级版用起来不错。 国内自己搭建解析服务是违法行为,所以这也是为什么使用dnspod的原因。 后台截图 开始使用 首先我们先进入dnspod的公共解析页面,点击开始使用。 专业版公共解析 dnspod会提供几种预设,我们选择「开发者」即可 开发者 然后你就成功的申请到自己个人使用的dns了! 更新拦截规则 我们可以将常见的广告过滤规则加入到dns中。我们在顶部选项卡中选择「拦截规则」。 拦截规则设置 打开adguard adguard 绑定iOS设备 推荐使用描述文件的方式,删除配置时删除描述文件即可。 描述文件 绑定macOS 推荐使用描述文件的方式,删除配置时删除描述文件即可。 描述文件 mac需要在「系统偏好设置」的「网络」中查看是否正在运行。 代理 如果没有运行需要点击「···」来启动服务。 启动服务 绑定路由器 找到自己路由器的DHCP设置,修改dns,然后记得绑定自己的ip。 修改dns 绑定ip 费用 目前有300万次/月的免费额度,但没有超出之后的价格。300万次一个人比较难用完,可以放心使用。 我个人使用iOS设备两台、智能家居、电脑两台,日均请求数大致2万/日。 判断是否搭建成功 可以通过查看日志的方式,日志大概有半小时到一小时的延迟,请耐心等待。