Mini programs can use react. How to use it: 1. Implement a renderer based on "react-reconciler" and generate a DSL; 2. Create a mini program component to parse and render DSL; 3. Install npm, and execute the build npm in the developer tools; 4. Introduce the package into your own page, and then use the API to complete the development.
The operating environment of this tutorial: Windows 10 system, react18.0.0 version, Dell G3 computer.
Can mini programs use react?
able.
Run React components directly in WeChat mini programs
When studying cross-end development, one of my important goals is to allow react components to run on In the WeChat applet. During this process, I explored the architecture of WeChat mini programs and aroused a lot of thinking. As for cross-end development, it is actually difficult to write once and run anywhere because the capabilities provided by each platform are different. For example, the WeChat applet provides native capabilities, such as turning on the camera or other functions that require a native environment. Supporting capabilities, although development in WeChat mini programs is also carried out in webview, it requires some native thinking. Therefore, there must be some restrictions to achieve write once. These restrictions determine that we cannot fully utilize the capabilities of the mini program and only use some layout capabilities. Therefore, I advise everyone to be mentally prepared when doing cross-terminal development. But if I break away from cross-end development and now I only develop small programs, can I use the react I am familiar with to develop it? Even, can I use the nautil framework I developed for development? The answer is yes, this article will take you step by step to realize your own react applet development, and help you complete the goal of migrating react projects to applet in certain specific scenarios.
Comparison of solutions for running React in mini programs
Currently, the industry can better support mini programs (unless otherwise specified, mini programs specifically refer to WeChat mini programs) to run React components. There are 3 sets of solutions, including taro from JD.com’s Above Lab, remax from a team at Ant Financial (the specific team name was not found), and kbone from a team at WeChat.
Taro
Compiled, the new version is also based on runtime
Parsed into wxml js
Old brand, continuous development, full platform support, continuous iteration
Remax
-
Runtime, with compiled macros
Based on reconciler
The most elegant, incremental update
-
Not mature enough, subsequent development is unknown
Kbone
When running, rely on webpack
Implement a set of DOM API by myself
Compatible with vue, even any framework based on DOM rendering
Performance issues (full inspection), almost stopped updating
3 sets of plans are different from each other, and they are all unique in their respective ideas. Personally, if you do not consider cross-end development, it is very valuable to implement a set of DOM API by yourself, because the DOM interface is an HTML standard, and you do not need to invent a set of standards yourself, and once it is implemented DOM API, then all other applications based on DOM can theoretically support running on it. However, its disadvantage is that every time you change a platform, you have to implement a set of DOM API for this platform. This cost is very high, because the DOM interface standard is extremely large and it is easy to have bugs during implementation. In my opinion, the most elegant implementation is Remax's idea, which is to make a renderer based on react-reconciler. This renderer abstracts the react component instance into a unified DSL, and parses and renders this DSL on different platforms. .
But after remax was updated iteratively, it began to rely heavily on its own compilation tools, which directly caused me to give up using it in the project. Because for our own projects, we may not actually need all of it. We only use react to complete certain parts of our entire small program (for example, some h5 that have been written in react we want to render to the small program) program, we still run other parts in the original project). If there is a dependence on its compilation tool, we will have to migrate the entire project to its compilation tool. Then I might as well just use taro, an old and stable tool.
Overall implementation idea
After some research, I decided to adopt the remax idea, which is to implement a renderer based on react-reconciler, generate a DSL, and then Create a small program component to parse and render this DSL. After completing the implementation, I built all these logics into the final product and published the product in the form of npm. For small program developers, they only need to install npm, execute the build npm in the developer tools, and then Introduce this package into your own page and use the API to complete development without the need to use additional compilation tools.
The biggest advantage of this solution is that it has weak (no) dependence on compilation tools, so that our solution can be run in any project without the need to introduce additional compilation tools to switch tool stacks. In addition, because the reconciler part has been packaged into the npm package, it is a module that can be run independently. Therefore, you can even use this npm package to render react components in Vue-style or mini-program native-style projects such as mpvue.
The idea of ??running react components in WeChat applet
As shown in the figure above, we create a react component through the renderer based on react-reconciler A pure object of DSL (including callback function) is obtained. In the js file of the page, we send this object to the rendering thread through this.setData. In wxml, we use a self-referential nested component we provide to perform DSL render. One thing to note here is that react-reconciler will trigger the corresponding hook when the component is updated. At this time, a new DSL will be generated again and the rendering will be sent through this.setData again. Therefore, the result of this renderer is different from that of simply using createElement. The renderer supports built-in functions of react such as hooks.
Next, I will explain the specific details so that you can hand-write the code described in this article as much as possible, so that you can achieve the same effect as this article in your own project. You can clone this warehouse locally, see the running effect, and study its entire implementation process.
Render react components as pure JS objects
The react renderer is essentially a side effect executor based on the react scheduling system. The results of the side effects are in the web environment It is the operation of DOM. In the native environment, it calls the rendering engine to rasterize the graphics. In the art environment, it calls the sound card to play the sound. In our plan this time, we need the renderer to generate a pure js object to facilitate the handover. The applet is passed as a message body between the two threads of the applet, and the interface is rendered in the applet based on this object.
Some students asked me: After jsx compilation, isn’t the execution result of React.createElement a pure JS object? Here you need to understand the essence of react. The components of react actually provide a description system for react, which describes the structure of the specific objects expressed by react. However, this description is abstract and only makes sense when you instantiate it and run it. The description we make in the component is not just the jsx part, it also includes business and program level logic. For example, in many scenarios, we need to decide which part of jsx to return based on the component status, so as to render different interfaces. This part of the content needs to rely on an environment for execution, which is the react renderer.
In the past, we could only simulate react-dom and write a renderer by ourselves according to its operating logic. Now, React has made a special library for its scheduler, react-reconciler, to help developers quickly access React's scheduling system so that they can build their own renderers. Here is a video (bring your own ladder) that introduces the basic usage and effects of react-reconciler.
import Reconciler from 'react-reconciler' const container = {} const HostConfig = { // ... 極其復雜的一個配置 } const reconcilerInstance = Reconciler(HostConfig) let rootContainerInstance = null export function render(element, { mounted, updated, created }) { if (!rootContainerInstance) { rootContainerInstance = reconcilerInstance.createContainer(container, false, false) } return reconcilerInstance.updateContainer(element, rootContainerInstance, null, () => { notify = { mounted, updated, created } created && created(container) mounted(container.data) }) }
In the above code, the specific content of HostConfig that is not given is the key. It is used to prepare a Reconciler. From a code perspective, it is a collection of hook functions. We need to configure it inside each hook function. Write some side effects to operate the container. You can see that at different times, the created, mounted, and updated we passed in will be called, and they receive the operated container, allowing us to obtain the js object (there are also containers on the container). There are some functions, but we can ignore them because this.setData will automatically clear them).
Because this configuration content is too complicated, it would take a lot of space to explain it clearly, so I directly paste the source code address here. You can understand what configuration items it has by reading the source code, and You can split this part of the code out, run a component of your own, and use console.log to observe the timing and order in which they are called.
In short, these interfaces are at the knowledge level, not complex logic. After understanding the role and execution timing of each configuration item, you can write your own renderer. In theory, it's not that difficult.
Based on react-reconciler, I have done some side effects in every aspect of react running. The essence of these side effects is to modify a pure js object. When react is run, it will go through a Life cycle, this is discussed in one of my videos about the specific process of react's life cycle. You can also follow my personal WeChat public account wwwtangshuangnet and discuss related issues with me. On each life cycle node, the scheduler will perform a side effect, that is, modify the pure js object I provided.
I provide two methods for obtaining the generated js object in the renderer of the mini program. After getting this js object, you can call this.setData of the applet and send this object to the rendering thread for rendering.
利用react渲染器得到的純對象上存在一些函數(shù),調用這些函數(shù)會觸發(fā)它們對應的邏輯(比如調用setState觸發(fā)hooks狀態(tài)更新),從而觸發(fā)調度器中的鉤子函數(shù)執(zhí)行,container對象再次被修改,updated被再次調用,this.setData被再次執(zhí)行,這樣,就實現(xiàn)了真正的react運行時在小程序中的植入。
嵌套遞歸自引用組件
渲染線程接收到this.setData發(fā)送過來的js對象后,如何將這個對象作為布局的信息,渲染到界面上呢?由于小程序的特殊架構,它為了安全起見,渲染線程中無法執(zhí)行可操作界面的腳本,所有的渲染,都得依靠模板語法和少量的wxs腳本。所以,要怎么做呢?
小程序提供了自定義組件的功能,在app.json或對應的page.json中,通過usingComponents來指定一個路徑,從而可以在wxml中使用這個組件。而有趣的地方在于,組件本身也可以在組件自己的component.json中使用usingComponents這個配置,而這個配置的內容,可以直接指向自己,例如,我在自己的組件中,這樣自引用:
// dynamic.json { "usingComponents": { "dynamic": "./dynamic" } }
自己引用自己作為組件之后,在其wxml中,我們就可以使用組件自己去渲染子級數(shù)據(jù),即一種嵌套遞歸的形式進行渲染。
我規(guī)定了一種特別的數(shù)據(jù)結構,大致如下:
{ type: 'view', props: { class: 'shadow-component', bindtap: (e) => { ... }, }, children: [ { type: 'view', props: {}, children: [ ... ], }, ], }
模板中,通過對type的判斷,選擇不同的模板代碼進行渲染。
<block wx:if="{{ type === 'view' }}"> <view class="{{ props.class }}" bindtap="bindtap"> <block wx:if="{{ children.length }}" wx:for="{{ children }}"> <dynamic data="{{ item }}" /> <!-- 嵌套遞歸 --> </block> </view> </block>
在wxml中把所有組件通過這種形式枚舉出來之后,這個組件就能按照上述的數(shù)據(jù)結構遞歸渲染出整個結構。
當然,這里還需要處理一些細節(jié),例如響應data的變化,事件響應函數(shù)等,你可以通過源碼了解具體要怎么處理。另外,微信小程序this.setData限制在1M以內,我雖然還沒有嘗試過很大的數(shù)據(jù),但是,這個限制肯定在將來是一個風險點,我現(xiàn)在還沒有解決,還在思考應該怎么最小化更新粒度。
不支持直接JSX的變通方法
小程序的編譯,沒有辦法自己配置支持新語法,所以如果我們在小程序代碼中使用jsx,就必須先走一遍自己的編譯邏輯。有兩種解決辦法,一種是不使用jsx語法,而是使用hyperscript標記語法,比如:
import { createElement as h } from 'react' function Some() { return h( 'view', { class: 'some-component' }, h( 'view', { class: 'sub-view' }, '一段文字', ), '一段文字', ) }
這樣的寫法顯然沒有直接寫jsx來的方便,但是閱讀上沒有什么障礙,且不需要將jsx編譯的過程。
另一種辦法是走一遍編譯,在小程序的頁面目錄下,創(chuàng)建一個頁面同名的.jsx文件,再利用bebel將它編譯為.js文件。但是這樣的話,你需要在發(fā)布小程序的時候,忽略掉所有的.jsx文件。另外,還有一個坑是,小程序的編譯不提供process.env,所以編譯react的結果用的時候會報錯。解決辦法是把react的cjs/react.production.min.js作為react的入口文件,通過小程序的構建npm的相關配置邏輯,指定react構建的文件。
結語
本文詳細講解了如何在微信小程序中直接運行react組件的思路,同時,你可以參考這個倉庫,運行效果看看,研究它的整個實現(xiàn)過程。總結而言,這個方法分為3個部分:1. 基于react-reconciler實現(xiàn)一個把react組件渲染為純js對象的渲染器,之所以需要純js對象,是因為小程序發(fā)送到渲染線程的數(shù)據(jù)必須是純對象。2. 利用小程序的自定義組件,實現(xiàn)自引用嵌套遞歸的組件,用于利用上一步得到的js對象渲染成真正的界面。3. 解決jsx問題,將前兩步的結果,在page中進行實施,以真正完成在小程序中渲染react組件的效果。當然,本文闡述過程,僅僅提供了這套思路,在真正用到項目中時,使用過程中肯定還會遇到一些坑,僅能作為原有小程序開發(fā)項目的補充手段,比如之前寫好的react組件不想重新寫成小程序版本,那么就可以使用這個方法,同時在渲染組件的地方,把DOM的標簽,映射為小程序的標簽,就可以在一定程度上解決原有react代碼復用的問題。如果你在實操過程中遇到什么問題,歡迎在本文下方留言討論~
文中鏈接: Nautil框架:https://github.com/tangshuang/nautil 演示倉庫:https://gitee.com/frustigor/wechat-dynamic-component Building a Custom React Rendere: https://www.youtube.com/watch?v=CGpMlWVcHok
推薦學習:《react視頻教程》
The above is the detailed content of Can small programs use react?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

With the popularity of mobile Internet technology and smartphones, WeChat has become an indispensable application in people's lives. WeChat mini programs allow people to directly use mini programs to solve some simple needs without downloading and installing applications. This article will introduce how to use Python to develop WeChat applet. 1. Preparation Before using Python to develop WeChat applet, you need to install the relevant Python library. It is recommended to use the two libraries wxpy and itchat here. wxpy is a WeChat machine

Implementing card flipping effects in WeChat mini programs In WeChat mini programs, implementing card flipping effects is a common animation effect that can improve user experience and the attractiveness of interface interactions. The following will introduce in detail how to implement the special effect of card flipping in the WeChat applet and provide relevant code examples. First, you need to define two card elements in the page layout file of the mini program, one for displaying the front content and one for displaying the back content. The specific sample code is as follows: <!--index.wxml-->&l

According to news from this site on October 31, on May 27 this year, Ant Group announced the launch of the "Chinese Character Picking Project", and recently ushered in new progress: Alipay launched the "Chinese Character Picking-Uncommon Characters" mini program to collect collections from the society Rare characters supplement the rare character library and provide different input experiences for rare characters to help improve the rare character input method in Alipay. Currently, users can enter the "Uncommon Characters" applet by searching for keywords such as "Chinese character pick-up" and "rare characters". In the mini program, users can submit pictures of rare characters that have not been recognized and entered by the system. After confirmation, Alipay engineers will make additional entries into the font library. This website noticed that users can also experience the latest word-splitting input method in the mini program. This input method is designed for rare words with unclear pronunciation. User dismantling

Mini programs can use react. How to use it: 1. Implement a renderer based on "react-reconciler" and generate a DSL; 2. Create a mini program component to parse and render DSL; 3. Install npm and execute the developer Build npm in the tool; 4. Introduce the package into your own page, and then use the API to complete the development.

How uniapp can achieve rapid conversion between mini programs and H5 requires specific code examples. In recent years, with the development of the mobile Internet and the popularity of smartphones, mini programs and H5 have become indispensable application forms. As a cross-platform development framework, uniapp can quickly realize the conversion between small programs and H5 based on a set of codes, greatly improving development efficiency. This article will introduce how uniapp can achieve rapid conversion between mini programs and H5, and give specific code examples. 1. Introduction to uniapp unia

This article brings you some related issues about WeChat mini programs. It mainly introduces how to use official account template messages in mini programs. Let’s take a look at them together. I hope it will be helpful to everyone.

Implementation idea: Establishing the server side of thread, so as to process the various functions of the chat room. The establishment of the x02 client is much simpler than the server. The function of the client is only to send and receive messages, and to enter specific characters according to specific rules. To achieve the use of different functions, therefore, on the client side, you only need to use two threads, one is dedicated to receiving messages, and the other is dedicated to sending messages. As for why not use one, that is because, only

Geolocation positioning and map display of PHP and mini programs Geolocation positioning and map display have become one of the necessary functions in modern technology. With the popularity of mobile devices, people's demand for positioning and map display is also increasing. During the development process, PHP and applets are two common technology choices. This article will introduce you to the implementation method of geographical location positioning and map display in PHP and mini programs, and attach corresponding code examples. 1. Geolocation in PHP In PHP, we can use third-party geolocation
