日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

React?Native?中限制導入某些組件和模塊的方法_React

作者:todoit ? 更新時間: 2022-09-27 編程語言

有些時候,我們不希望使用某些組件,而是想使用其他組件。這時候,我們可以使用一個名為?no-restricted-imports?的eslint 規則,該規則允許你指定一個或多個組件的名稱,以防止使用這些組件。

no-restricted-imports?是 eslint 自帶的一個規則,我們不需要額外引入一個插件。

限制使用 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?。

經過作者?一番調研?,發現可以使用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 能滿足需求,則優先使用它。

示例

這里有?一個示例?,供你參考。

原文鏈接:https://juejin.cn/post/7127057745081008165

欄目分類
最近更新