React?Native?中限制導入某些組件和模塊的方法
有些時候,我們不希望使用某些組件,而是想使用其他組件。這時候,我們可以使用一個名為 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 來達到更精確的控制導入目的:
// .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",
},
],
},
}效果如下圖所示:


當然,對于要限定的某些模塊,如果 no-restricted-imports 能滿足需求,則優(yōu)先使用它。
示例
這里有 一個示例 ,供你參考。
到此這篇關于React Native 中限制導入某些組件和模塊的方法的文章就介紹到這了,更多相關React Native 限制導入內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
詳解React如何優(yōu)雅地根據(jù)prop更新state值
這篇文章主要為大家詳細介紹了React如何優(yōu)雅地實現(xiàn)根據(jù)prop更新state值,文中的示例代碼講解詳細,具有一定的參考價值,感興趣的小伙伴可以了解下2023-11-11
解決React報錯JSX?element?type?does?not?have?any?construct
這篇文章主要為大家介紹了解決React報錯JSX?element?type?does?not?have?any?construct?or?call?signatures,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-12-12

