【问题标题】:Importing/exporting styled components in React causes invalid hook calls在 React 中导入/导出样式化组件会导致无效的挂钩调用
【发布时间】:2023-02-09 22:41:29
【问题描述】:

我正在研究一个 React 项目(react@18.2.0,styled-components@5.1.1),该项目已设置为使用 styled-components,以便从 common/styled.js 文件中导出常用组件,但是导致大量无效挂钩调用错误。

现在,它看起来像这样:

export const ExampleButton = styled.button`
  color: white;
`;

然后在需要的地方导入那些样式化的组件,就像这样:

import { ExampleButton, SomeComponent, AnotherComponent } from '../common.styled';

我知道它们无效的挂钩调用是由这种导出/导入设置引起的,因为当我将某个特定样式组件从 common/styled.js 中删除并将其粘贴到需要的地方时,该样式组件的错误消息消失了,所以不用这个:

import { ExampleButton } from '../common.styled';

const ExampleComponent = () => {
  return (
    <div>
       <ExampleButton>Hello</ExampleButton>
    </div>
  );
};

我这样做:

import styled from 'styled-components';

const ExampleComponent = () => {
  const ExampleButton = styled.button`
    color: white;
  `;

  return (
    <div>
      <ExampleButton>Hello</ExampleButton>
    </div>
  );
};

所以这行得通,但它并不是一个真正可行的解决方案,因为我必须在所有地方粘贴相同的代码,而不仅仅是 ExampleComponent,并且对整个项目这样做会导致大量的代码重复。

以不违反挂钩规则的方式在此处创建类似于 common/styled.js 的解决方案的正确方法是什么?

【问题讨论】:

  • 请详细说明您得到的是哪种无效挂钩调用错误。
  • 错误消息显示“警告:无效的挂钩调用。挂钩只能在函数组件的主体内部调用。”并且堆栈跟踪始终包含一个文件,其中在函数组件主体之外定义了样式组件,在这种情况下通常是 ./src/common/styled.js。
  • 它在抱怨哪个钩子?
  • 堆栈跟踪在一行中引用了 useRef 挂钩:useRef @ react.development.js:1629。除此之外,以及一些关于无效挂钩调用的一般性宣传,错误消息并没有详细说明。
  • React 17 也会发生这种情况吗?

标签: reactjs styled-components


【解决方案1】:

似乎在某些旧版本的 styled-components 和 React 18 之间存在问题,solved in v5.3.1
https://github.com/styled-components/styled-components/pull/3564

也许将 styled-components 升级到 v5.3.1 或更高版本可以解决问题。

【讨论】:

    猜你喜欢
    • 2023-02-09
    • 2021-07-25
    • 2022-01-20
    • 1970-01-01
    • 2020-06-27
    • 2020-01-14
    • 2019-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多