reactjs 在React中导入/导出样式化组件会导致无效的挂接调用

46qrfjad  于 2023-02-12  发布在  React
关注(0)|答案(1)|浏览(144)

我正在处理一个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的解决方案的正确方法是什么?

ux6nzvsh

ux6nzvsh1#

在样式化组件的一些旧版本和React 18之间似乎存在问题,该问题已在v5.3.1中得到解决。
https://github.com/styled-components/styled-components/pull/3564
也许将样式化组件升级到v5.3.1或更高版本可以解决这个问题。

相关问题