direflow落地分享-以React方式写WebComponents

简介: direflow落地分享-以React方式写WebComponents
React大家都很熟悉,WebComponents估计也有所耳闻。那么React+WebComponents会碰撞出怎样的火花呢?

其实有这样一个开源框架,支持React方式写组件,最终打包后的产物为WebComponents。

它就是direflow,这个框架支持React方式写WebComponents。

框架地址:https://github.com/Silind-Sof...



为什么选择direflow


开源社区有很多WebComponents框架,比如stencil、lit等等,这些框架社区活跃度高、落地实践多,但是它们都存在一些不符合我们场景的问题:

  • 都具有自己的一套DSL,具有一定的学习成本
  • 缺少基于AntD等React技术栈的最佳实践

而基于React实现的direflow,可以完美避免上面的问题。

  • React方式写组件,零学习成本增加
  • 基于Webpack打包,AntD等React技术栈可以直接使用


落地分析


落地WebComponents有一段时间了,目前我们落地了几个场景,对开发效率提升是非常大的,极大程度地降低了业务线接入成本,因此阶段性地做一个总结。



image.png


假设有这样一个web component组件。

<test-component name="jack" age="18" />


原理分析


完整构建步骤


一个完整的direflow web component组件,包含以下步骤。

  1. 创建一个web component标签
  2. 创建一个React组件,将attributes转化为properties属性转化并传入React组件(通过Object.defineProperty做劫持,通过attributeChangedCallback做attribute实时刷新)
  3. 将这个React应用,挂载到web component的shadowRoot

<img width="592" alt="direflow" src="https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/7062464f9cfb469f9b92f63c471108c3~tplv-k3u1fbpfcp-zoom-1.image">


下面再来详细分析一下:


假设direflow的配置如下:


import { DireflowComponent } from "direflow-component";
import  App from "./app";
export default DireflowComponent.create({
  component: App,
  configuration: {
    tagname: "test-component",
    useShadow: true,
  },
});


创建一个Web component

const WebComponent = new WebComponentFactory(
  componentProperties,
  component,
  shadow,
  anonymousSlot,
  plugins,
  callback,
).create();
customElements.define(tagName, WebComponent);

通过customElements.define声明一个web component,tagName为"test-component",WebComponent为集成了渲染react组件能力的的web components工厂函数实例。


web components工厂函数


响应式


劫持所有属性。


public subscribeToProperties() {
  const propertyMap = {} as PropertyDescriptorMap;
  Object.keys(this.initialProperties).forEach((key: string) => {
    propertyMap[key] = {
      configurable: true,
      enumerable: true,
      set: (newValue: unknown) => {
        const oldValue = this.properties.hasOwnProperty(key)
          ? this.properties[key]
          : this.initialProperties[key];
        this.propertyChangedCallback(key, oldValue, newValue);
      },
    };
  });
  Object.defineProperties(this, propertyMap);
}

首先,将attributes转化为properties。

其次,通过Object.defineProperties劫持properties,在setter中,触发propertyChangedCallback函数。


const componentProperties = {
  ...componentConfig?.properties,
  ...component.properties,
  ...component.defaultProps,
};

上面这段代码中的property变化时,重新挂载React组件。(这里一般是为了开发环境下,获取最新的视图)

/**
 * When a property is changed, this callback function is called.
 */
public propertyChangedCallback(name: string, oldValue: unknown, newValue: unknown) {
  this.properties[name] = newValue;
  this.mountReactApp();
}


attribute变化时,重新挂载组件,此时触发的是web components原生的attributeChangedCallback。

public attributeChangedCallback(name: string, oldValue: string, newValue: string) {
  const propertyName = factory.componentAttributes[name].property;
  this.properties[propertyName] = getSerialized(newValue);
  this.mountReactApp();
}


创建一个React组件


对应上面的this.mountReactApp。

<EventProvider>
  {React.createElement(factory.rootComponent, this.reactProps(), anonymousSlot)}
<EventProvider>
  • EventProvider-创建了一个Event Context包裹组件,用于web components组件与外部通信。
  • factory.rootComponent-将DireflowComponent.create的component传入,作为根组件,并且通过React.createElement去创建。
  • this.reactProps()-获得序列化后的属性。为什么要序列化,因为html标签的attribute,只接收string类型。因此需要通过JSON.stringify()序列化传值,工厂函数内部会做JSON.parse。将attribute转化为property
  • anonymousSlot-匿名slot,插槽。可以直接将内容分发在web component标签内部。


挂载React应用到web component


const root = createProxyRoot(this, shadowChildren);
ReactDOM.render(<root.open>{applicationWithPlugins}</root.open>, this);


代理组件将React组件作为children,ReactDOM渲染这个代理组件。


创建一个代理组件


主要是将Web Component化后的React组件,挂载到web component的shadowRoot。


const createProxyComponent = (options: IComponentOptions) => {
  const ShadowRoot: FC<IShadowComponent> = (props) => {
    const shadowedRoot = options.webComponent.shadowRoot
      || options.webComponent.attachShadow({ mode: options.mode });
    options.shadowChildren.forEach((child) => {
      shadowedRoot.appendChild(child);
    });
    return <Portal targetElement={shadowedRoot}>{props.children}</Portal>;
  };
  return ShadowRoot;
};

获取到shadowRoot,没有的话attachShadow新建一个shadow root。

将子结点添加到shadow root。

返回一个挂载组件到shadow root的Portal,接收children的高阶函数。


思考


为什么要每一次attribute变化都要重新挂载React App?不能把它看做一个常规的react组件吗,使用react自身的刷新能力?


因为direflow的最终产物,是一个web component组件。


attribute变化,react是无法自动感知到这个变化的,因此需要通过监听attribute变化去重新挂载React App。


但是!React组件内部,是完全可以拥有响应式能力的,因为


direflow是一个什么框架?



其实,direflow本质上,是一个 React组件 + web component +web component属性变化重新挂载React组件的 web component框架。


所以,direflow的响应式其实分为2块:

组件内部响应式(通过React自身响应式流程),组件外部响应式(WebComponents属性变化监听重渲染组件)。


如果外部属性不会经常变化的话,性能这块没有问题,因为组件内部的响应式完全是走了React自身的响应式。


属性外部属性如果会经常变化的话,direflow框架在这块还有一定的优化空间。



相关文章
|
XML 移动开发 前端开发
用 React 结合 SAP UI5 Web Components 来开发 SAP Fiori 应用
用 React 结合 SAP UI5 Web Components 来开发 SAP Fiori 应用
153 0
用 React 结合 SAP UI5 Web Components 来开发 SAP Fiori 应用
|
前端开发 JavaScript 安全
从 React Hooks 理解 Web components 的生命周期
从 React Hooks 理解 Web components 的生命周期
421 0
|
9月前
|
前端开发
前端学习笔记202305学习笔记第二十九天-React keep alive原理之2
前端学习笔记202305学习笔记第二十九天-React keep alive原理之2
42 0
|
9月前
|
前端开发
前端学习笔记202306学习笔记第四十八天-react-admin marmelab之8
前端学习笔记202306学习笔记第四十八天-react-admin marmelab之7
30 0
|
6天前
|
前端开发 JavaScript
前端知识笔记(二十六)———React如何像Vue一样将css和js写在同一文件
前端知识笔记(二十六)———React如何像Vue一样将css和js写在同一文件
33 1
|
6月前
|
前端开发
前端笔记:React的form表单全部置空或者某个操作框置空的做法
在React框架前端开发中,经常会有弹出框的开发,涉及到弹出框,难免就会有表单。一般在关闭弹出框或者对表单联动时,往往都需要考虑对表单进行置空操作了。
51 0
|
9月前
|
Web App开发 前端开发 JavaScript
前端学习笔记202307学习笔记第五十七天-模拟面试笔记react-fiber解决了什么问题
前端学习笔记202307学习笔记第五十七天-模拟面试笔记react-fiber解决了什么问题
51 0
|
9月前
|
JavaScript 前端开发 调度
前端学习笔记202307学习笔记第五十七天-模拟面试笔记react-fiber和虚拟dom关系
前端学习笔记202307学习笔记第五十七天-模拟面试笔记react-fiber和虚拟dom关系
79 0
|
9月前
|
前端开发
前端学习笔记202305学习笔记第二十九天-React keep alive原理之1
前端学习笔记202305学习笔记第二十九天-React keep alive原理之1
34 0
|
9月前
|
前端开发
前端学习笔记202305学习笔记第二十九天-React keep alive原理之4
前端学习笔记202305学习笔记第二十九天-React keep alive原理之4
31 0

热门文章

最新文章