首页 > 解决方案 > 在 npm 包中使用 styled-component 时出现奇怪的问题

问题描述

我正在尝试创建一个 npm 包 - 一个 UI 组件。

假设我有一个名为 的项目fancy-web,并且 npm 包名为fancy-components.

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 测试组件中,如果我正在做

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;


不知道这里出了什么问题,非常感谢任何帮助。

标签: reactjsreact-hooksstyled-components

解决方案


事实证明,因为我正在做导致问题的链接。在我将其推出而不是进行链接之后,一切正常。


推荐阅读