Meta 最新開源!面向 Web 和 Native 的跨平臺 React 解決方案
大家好,我是 ConardLi。
最近,Meta 開源了一個新的庫,叫做 react-strict-dom
,其目標是改進和標準化編寫用於 Web
和 Native
的通用 React
組件的方式。
在 React Native
中,用於渲染 UI 的原始組件和 Web 不同,如果你是一個 Web 開發者,看到基礎的 React Native
組件一開始可能會覺得有點奇怪,也難以使用:
import { View, Text } from "react-native";
const App = () => {
return (
<View>
<Text>你好, code祕密花園!</Text>
</View>
);
};
此外,它還移除了在 React Native
中使用使用 Web 原生的 UI 庫的能力,從 Web 遷移組件需要花費很多時間,並且非常痛苦。
react-native-web
幾年前,在 Twitter
的 Progressive Web
應用的開發過程中,尼古拉斯 · 加拉格爾(Nicolas Gallagher)創造了 React Native for Web
。RNW
添加了一個兼容改進,將 Ract Native
的代碼轉譯爲 react-dom
的代碼,使我們能夠在 Web
上渲染 React Native
組件:
但是,這種方式也有相當多的缺點:
-
實現了大片分散的 API,需要匹配
React Native
的非標準實現(例如事件)。 -
庫本身也相當大,這對現代 Web 應用來說並不是最好的選擇。
react-strict-dom 的方法是什麼?
react-strict-dom
採取了與 React Native for Web
相反的方法,它使用 Web API 來渲染組件。爲此,它添加了兩個小型的 polyfill
,負責將其 API 轉譯成 react-native
和 react-dom
代碼。下面的架構圖詳細展示了它是如何工作的:
目前,並不是所有的 API 都在 Native 平臺內部內置,但是開發者們也正在努力兼容中。
這個表格展示了當前的兼容性的進度:https://github.com/facebook/react-strict-dom/blob/main/packages/react-strict-dom/COMPATIBILITY.md
使用 react-strict-dom 創建組件
react-strict-dom
是由 Meta 創建的新樣式解決方案,由 stylex
提供支持,它已經在 facebook.com 的生產環境中開始使用了。我們可以用來構建應用的所有模塊都可以在 html
下找到,以下是使用 RSD 構建 UI 的一個例子:
import React from "react";
import { css, html } from "react-strict-dom";
// Part of apps/examples/src/App.js
export default function App() {
return (
<html.div style={styles.div}>
<html.div data-testid="testid">div</html.div>
<html.span>span</html.span>
<html.p>paragraph</html.p>
<html.div />
<html.span>
<html.a href="https://google.com">anchor</html.a>,
<html.code>code</html.code>,<html.em>em</html.em>,
<html.strong>strong</html.strong>,
<html.span>
H<html.sub>2</html.sub>0
</html.span>
,<html.span>
E=mc<html.sup>2</html.sup>
</html.span>
</html.span>
</html.div>
);
}
// This is calling `stylex` under the hood
const styles = css.create({
div: {
paddingBottom: 50,
paddingTop: 50,
backgroundColor: "white",
},
});
react-strict-dom
利用我們熟知的 Web API
來構建 Web
和 Native
通用的應用程序。
<html.div>
是一個原生組件嗎?
是的,它是! react-strict-dom
的角色是將一個通用 API 轉譯成各個平臺的原始代碼。
在 React Native Principles
博客文章中寫到:
我們對
React Native
的最高優先級是符合人們對每個平臺的期望。這就是爲什麼 React Native 會渲染成平臺原生代碼。我們重視原生的外觀和感覺,而不是跨平臺的一致性。
React Native
的目標是創建完全的原生應用,所以,使用新的方法,我們最終還是能創建一個完全的原生應用,而不是 WebView
或其他任何東西。我們可以通過在存儲庫中運行示例應用並使用 Xcode 的視圖層次工具來檢查組件,輕鬆驗證這一點:
Nicolas 的 RFC:RFC: React DOM for Native
(https://github.com/react-native-community/discussions-and-proposals/pull/496) 詳細介紹了方案的原理,感興趣可以深入閱讀一下。
react-strict-dom
正在幫助 Meta
的團隊更快地實現功能,使用更少的工程師,發佈到更多平臺,這也是 Meta 直接發起的第一個面向 Web
和 Native
的跨平臺 React
解決方案!
對此,你怎麼看?
最後
參考:
-
https://github.com/facebook/react-strict-dom/
-
https://szymonrybczak.dev/blog/react-strict-dom#what-is-react-strict-dom-approach
-
https://github.com/react-native-community/discussions-and-proposals/pull/496
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/hO2PzBs2uAEGr4rt4m1tLw