使用Material UI会导致无效的挂接调用警告

时间:2019-03-19 18:49:51

标签: reactjs material-ui react-hooks rollupjs

我正在尝试create-react-library捆绑可重用的库。我正在尝试的想法是创建可组合的组件库,以供我们在Web应用程序和电子应用程序中使用。

在package.json文件中,我们具有以下要求

"peerDependencies": {
    "react": "^15.0.0 || ^16.0.0",
    "react-dom": "^15.0.0 || ^16.0.0"
},
"devDependencies": {
    "@material-ui/core": "^4.0.0-alpha.4",
    ....
    "react": "^16.4.1",
    "react-dom": "^16.4.1",
}

当我导入Material UI组件时,会导致错误

  

只能在函数组件的主体内部调用挂钩。 https://reactjs.org/warnings/invalid-hook-call-warning.html

这是完整的组件(这只是我正在慢慢扩展的create-react-library中的示例)

import React, { Component } from 'react'
import PropTypes from 'prop-types'

import { Button } from "@material-ui/core";

import styles from './styles.css'

class ExampleComponent extends Component {
  static propTypes = {
    text: PropTypes.string
  }

  render() {
    const { text } = this.props

    return (

        <div className="">
          <Button></Button>
          Example Component: {text}
        </div>
    )
  }
}

export default ExampleComponent;

**********************************编辑************ **********************

更改材料ui的devDependencies并做出反应,然后将其添加到rollup.config.js文件中(以解决此问题)修复错误

"devDependencies": {
    "@material-ui/core": "^3.9.0",
    ...
    "react": "^16.7.0",
    "react-dom": "^16.7.0",
   }

rollup.config.js

commonjs({
  include: 'node_modules/**',
  namedExports: {
    'node_modules/@material-ui/core/styles/index.js': [
      'createGenerateClassName',
      'createMuiTheme',
      'createStyles',
      'jssPreset',
      'MuiThemeProvider',
      'withStyles',
      'withTheme'
    ],
    'node_modules/@material-ui/core/Modal/index.js': [ 'ModalManager' ]
  }
})

1 个答案:

答案 0 :(得分:1)

在我的情况下,我安装了一个带有node_modules文件夹的子模块,实际上我将两次React编译成一个包。

通过删除子模块的node_modules 文件夹进行修复,也可能会在Webpack配置中修复:

   main
      node_modules
      submodules
          -> node_modules