首页 > 解决方案 > React 函数式组件与 useState Hook Breaks 组件库

问题描述

我正在创建一个自定义反应组件库,我遇到了一个我认为必须与我的包的创建方式有关的问题。当我将一个使用“useState”挂钩的功能组件添加到我的库中并将其作为依赖项导入另一个项目时,我收到“无效的挂钩调用”。我已经检查了错误中可能导致错误的三种可能情况,并消除了所有这些情况。当我将有问题的组件复制到我的主项目目录并直接导入它(而不是通过我的自定义反应组件包)时,它按预期工作,所以我在创建包时显然做错了什么,我无法确定什么。

我的 webpack.config.js 文件如下所示:

const path = require('path');

module.exports = {
  mode: 'production',
  entry: './src/index.js',
  output: {
    path: path.resolve('dist'),
    filename: 'index.js',
    libraryTarget: 'commonjs2',
    path: path.resolve(__dirname, './dist/'),
    publicPath: '/',
  },
  module: {
    rules: [
      {
        test: /\.js?$/,
        exclude: /(node_modules)/,
        use: 'babel-loader',
      },
    ],
  },
  externals: ['react', 'react-dom'],
};

我的 bable.rc 文件:


{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react"
  ],
  "plugins": [
    [
      "@babel/plugin-transform-runtime",
      {
        "useESModules": true,
        "regenerator": false
      }
    ],
    "@babel/plugin-proposal-class-properties",
    "@babel/plugin-transform-react-constant-elements"
  ]
}

我的 package.json 文件:


{...
"scripts": {
    "test": "jest",
    "build": "webpack",
    "lint": "eslint . --ext js",
    "stylelint": "stylelint **/*.*css --ip **/*.min.css -s scss"
  },
  "files": [
    "dist"
  ],
  "peerDependencies": {
    "react": "^16.12.0",
    "react-dom": "^16.12.0"
  },
  "devDependencies": {
    "@babel/core": "^7.12.3",
    "@babel/plugin-proposal-class-properties": "^7.12.1",
    "@babel/plugin-transform-react-constant-elements": "^7.12.13",
    "@babel/plugin-transform-runtime": "^7.12.1",
    "@babel/preset-env": "^7.12.1",
    "@babel/preset-react": "^7.12.5",
    "@commitlint/cli": "^11.0.0",
    "@commitlint/config-conventional": "^11.0.0",
    "babel": "^6.23.0",
    "babel-eslint": "^11.0.0-beta.2",
    "babel-jest": "^26.6.3",
    "babel-loader": "^8.2.1",
    "concurrently": "^5.3.0",
    "css-loader": "^5.0.1",
    "eslint": "^7.14.0",
    "eslint-config-google": "^0.14.0",
    "eslint-config-react-important-stuff": "^2.0.0",
    "eslint-plugin-babel": "^5.3.1",
    "eslint-plugin-react": "^7.21.5",
    "file-loader": "^6.2.0",
    "husky": "^4.3.0",
    "jest": "^26.6.3",
    "node-sass": "^5.0.0",
    "prop-types": "^15.7.2",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "sass-loader": "^10.1.0",
    "semantic-release": "^17.3.0",
    "style-loader": "^2.0.0",
    "stylelint": "^13.8.0",
    "stylelint-config-standard": "^20.0.0",
    "tinycolor2": "^1.4.2",
    "webpack": "^5.5.1",
    "webpack-cli": "^4.2.0"
  },
  "dependencies": {
    "react-color": "^2.19.3"
  }
}

标签: reactjsreact-hooksreact-functional-component

解决方案


推荐阅读