【发布时间】: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 也会发生这种情况吗?