当我从样式组件中使用我自己的库时出现无效的钩子调用错误

Posted

技术标签:

【中文标题】当我从样式组件中使用我自己的库时出现无效的钩子调用错误【英文标题】:Invalid hook call error when I use my own library from styled-components 【发布时间】:2020-10-20 23:11:53 【问题描述】:

我从 styled-components 库创建了自己的 UI 工具(使用 typescript 和 rollup)。

例如,我有以下组件:

import styled from 'styled-components'

export const MyUITest2 = styled.div`
  color: red;
`

所以,我在另一个项目中使用了这个组件:

<MyUITest2>This is my test</MyUITest2>

而且,当我运行应用程序时,我得到:

The above error occurred in the <styled.div> component:
    in styled.div (at ...)
...

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See ... react-invalid-hook-call for tips about how to debug and fix this problem.

我认为 styled-components 存在问题,因为当我使用没有 styled-components 的 simple 时,我的组件会显示在应用程序上。

这里是我的 github 存储库: https://github.com/aehp20/ionic-react-my-ui-components

提前谢谢你!

【问题讨论】:

你有没有找到解决这个@Aron的方法? 【参考方案1】:

检查您的 package.json 并确保 reactreact-dom 不存在于依赖项中,而是将它们都添加到 peerDependencies

当有两个不同的 react 实例运行时会发生此错误,因此如果您在 UI 库中安装了 react,那么它将与您实现 UI 库的项目的 react 版本发生冲突。

【讨论】:

以上是关于当我从样式组件中使用我自己的库时出现无效的钩子调用错误的主要内容,如果未能解决你的问题,请参考以下文章

在 React 中使用 material-ui makeStyles 的钩子调用无效

Reactjs,使用材质UI:无效的钩子调用错误

使用 Material UI 导致无效的钩子调用警告

无效的钩子调用错误:只能在函数组件的主体内部调用钩子

System.Xml.XmlException '根级别的数据无效,第 1 行,位置 1' 当我从 1 个 xml 文件更改为 5 时出现错误

React Hooks Mobx:无效的钩子调用。 Hooks 只能在函数组件的主体内部调用