【发布时间】:2020-10-04 11:45:35
【问题描述】:
我正在尝试创建一个 npm 包 - 一个 UI 组件。
假设我有一个名为 fancy-web 的项目,以及名为 fancy-components 的 npm 包。
在fancy-web中,我包含在package.json中
"fancy-components": "^0.0.1"
(换句话说,fancy-web 将消耗fancy-components)。
在fancy-web,我有
// ...
import { ThemeProvider } from 'styled-components';
import { Testing } from 'fancy-components';
// ...
return (
<ThemeProvider theme={theme}>
<Testing />
</ThemeProvider>
)
问题出在这里
在我的fancy-components Testing 组件中,如果我在做的话
If I'm doing something trivial like this in the Testing component, I will get an error
Uncaught 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
---
import React from 'react';
import styled from 'styled-components';
const Container = styled.div`
margin-top: 40px;
`;
function Testing(props: Props): JSX.Element {
return (
<Container>
<div>Testing</div>
</Container>
);
}
export default Testing;
However, the following works if my "Testing" component just like that.
The following is the `Testing` code
---
import React from 'react';
import styled from 'styled-components';
function Testing(props: Props): JSX.Element {
return (
<div>Testing</div>
);
}
export default Testing;
不确定这里出了什么问题,非常感谢任何帮助。
【问题讨论】:
-
您使用的样式组件版本似乎与钩子不兼容,或者您的反应版本与钩子不兼容
-
请显示整个代码而不是 sn-ps... 它在
Testing实现中很明显 -
@ShubhamKhatri 我在两个项目中都使用了
"styled-components": "^5.0.0"。我的反应是"react": "^16.8.6",@DennisVash 我更新了Testing代码。 -
报错信息很清楚,这是整个代码吗?我认为我们需要更多信息来找出问题
-
尝试在沙箱中重现问题:codesandbox.io/s/vanilla-react-template-irhcq,您的代码没有表明任何问题
标签: reactjs react-hooks styled-components