首页 > 解决方案 > 当我从样式组件中使用我自己的库时出现无效的钩子调用错误

问题描述

我从 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.

我认为样式组件存在问题,因为当我使用没有样式组件的简单组件时,我的组件会显示在应用程序上。

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

先感谢您!

标签: reactjstypescriptstyled-componentsrollup

解决方案


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

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


推荐阅读