React?Native?中限制導(dǎo)入某些組件和模塊的方法
有些時候,我們不希望使用某些組件,而是想使用其他組件。這時候,我們可以使用一個名為 no-restricted-imports 的eslint 規(guī)則,該規(guī)則允許你指定一個或多個組件的名稱,以防止使用這些組件。
no-restricted-imports
是 eslint 自帶的一個規(guī)則,我們不需要額外引入一個插件。
限制使用 Touchable
假如我們希望小伙伴們不要使用 Touchable
系列組件,而是使用 Pressable
組件,那么我們可以這樣寫:
// .eslintrc.js module.exports = { rules: { "no-restricted-imports": [ "error", { paths: [ { name: "react-native", importNames: [ "TouchableOpacity", "TouchableHighlight", "TouchableWithoutFeedback", "TouchableNativeFeedback", ], message: "Use Pressable instead", }, ], }, ], }, }
限制使用 Image
又譬如,我們希望小伙伴們使用 FastImage 組件,而不是使用 Image
組件,那么我們可以這樣寫:
// .eslintrc.js module.exports = { rules: { "no-restricted-imports": [ "error", { paths: [ { name: "react-native", importNames: ["Image"], message: "Use FastImage from react-native-fast-image instead", }, ], }, ], }, }
同時限制兩者
如果我們既要限制使用 Touchable
組件,又要限制使用 Image
組件,那么我們可以這樣寫:
// .eslintrc.js module.exports = { rules: { "no-restricted-imports": [ "error", { paths: [ { name: "react-native", importNames: [ "TouchableOpacity", "TouchableHighlight", "TouchableWithoutFeedback", "TouchableNativeFeedback", "Image", ], message: "這個提示怎么寫?", }, ], }, ], }, }
但問題是, message
怎么寫?
我們希望,如果小伙伴使用 Touchable
組件,那么就提示他 Use Pressable instead ,如果小伙伴使用 Image
組件,那么就提示他 Use FastImage from react-native-fast-image instead 。
經(jīng)過作者 一番調(diào)研 ,發(fā)現(xiàn)可以使用no-restricted-syntax 來達(dá)到更精確的控制導(dǎo)入目的:
// .eslintrc.js module.exports = { rules: { "no-restricted-syntax": [ "error", { selector: "ImportDeclaration[source.value='react-native'] > ImportSpecifier[imported.name=/Touchable\\w*/]", message: "Use Pressable instead", }, { selector: "ImportDeclaration[source.value='react-native'] > ImportSpecifier[imported.name='Image']", message: "Use FastImage from react-native-fast-image instead", }, ], }, }
效果如下圖所示:
當(dāng)然,對于要限定的某些模塊,如果 no-restricted-imports 能滿足需求,則優(yōu)先使用它。
示例
這里有 一個示例 ,供你參考。
到此這篇關(guān)于React Native 中限制導(dǎo)入某些組件和模塊的方法的文章就介紹到這了,更多相關(guān)React Native 限制導(dǎo)入內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
React Native全面屏狀態(tài)欄和底部導(dǎo)航欄適配教程詳細(xì)講解
最近在寫 React Native 項目,調(diào)試應(yīng)用時發(fā)現(xiàn)頂部狀態(tài)欄和底部全面屏手勢指示條區(qū)域不是透明的,看起來很難受。研究了一下這個問題,現(xiàn)在總結(jié)一下解決方案,這篇文章主要介紹了React Native全面屏狀態(tài)欄和底部導(dǎo)航欄適配教程2023-01-01react中關(guān)于函數(shù)調(diào)用()與bind this的原因及分析
這篇文章主要介紹了react中關(guān)于函數(shù)調(diào)用()與bind this的原因及分析,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02ReactiveCocoa代碼實踐之-UI組件的RAC信號操作
這篇文章主要介紹了ReactiveCocoa代碼實踐之-UI組件的RAC信號操作 的相關(guān)資料,需要的朋友可以參考下2016-04-04React找不到模塊“./index.module.scss”或其相應(yīng)的類型聲明及解決方法
這篇文章主要介紹了React找不到模塊“./index.module.scss”或其相應(yīng)的類型聲明及解決方法,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-09-09