如何在styled-components中结合TypeScript对象语法使用shouldForwardProps
在TypeScript中使用styled-components对象语法时,如何正确配置shouldForwardProp?
我尝试了各种方法,但始终搞不清正确语法,以下是我的代码和遇到的错误:
带配置的错误尝试
const BASE_CONFIG = { shouldForwardProp: ( prop: string, defaultValidatorFn: (prop: string) => boolean ) => prop !== 'isSmallContainer' && defaultValidatorFn(prop), }; const Thing = styled( 'div', BASE_CONFIG )<{ isSmallContainer: boolean; }>(({ isSmallContainer }) => ({ padding: isSmallContainer ? 12 : '16px 32px', display: 'flex', alignItems: 'center', }));
Expected 1 arguments, but got 2.
可正常运行的原始代码(无配置)
const Thing = styled.div<{ isSmallContainer: boolean; }>(({ isSmallContainer }) => ({ padding: isSmallContainer ? 12 : '16px 32px', display: 'flex', alignItems: 'center', }));
其他错误尝试
尝试1
const Thing = styled .div<{ isSmallContainer: boolean; }>(({ isSmallContainer }) => ({ padding: isSmallContainer ? 12 : '16px 32px', display: 'flex', alignItems: 'center', })) .withConfig(BASE_CONFIG);
This expression is not callable. Type 'never' has no call signatures.
尝试2
const Thing = styled .div<{ isSmallContainer: boolean; }>.withConfig(BASE_CONFIG)(({ isSmallContainer }) => ({ padding: isSmallContainer ? 12 : '16px 32px', display: 'flex', alignItems: 'center', }));
An instantiation expression cannot be followed by a property access.
尝试3
const Thing = styled.withConfig(BASE_CONFIG).div<{ isSmallContainer: boolean; }>(({ isSmallContainer }) => ({ padding: isSmallContainer ? 12 : '16px 32px', display: 'flex', alignItems: 'center', }));
Property 'withConfig' does not exist on type 'StyledInterface'.
请问在使用TypeScript语法和对象表示法(而非styled-components模板字符串)时,应该将配置放在哪里?
正确解法
方法1:先创建带配置的工厂,再定义组件
import styled from 'styled-components'; const BASE_CONFIG = { shouldForwardProp: ( prop: string, defaultValidatorFn: (prop: string) => boolean ) => prop !== 'isSmallContainer' && defaultValidatorFn(prop), }; // 先生成带配置的styled工厂实例 const styledWithConfig = styled.withConfig(BASE_CONFIG); // 使用该工厂创建组件并指定泛型类型 const Thing = styledWithConfig.div<{ isSmallContainer: boolean }>(({ isSmallContainer }) => ({ padding: isSmallContainer ? 12 : '16px 32px', display: 'flex', alignItems: 'center', }));
方法2:链式调用时调整泛型位置
import styled from 'styled-components'; const BASE_CONFIG = { shouldForwardProp: ( prop: string, defaultValidatorFn: (prop: string) => boolean ) => prop !== 'isSmallContainer' && defaultValidatorFn(prop), }; const Thing = styled.withConfig(BASE_CONFIG)<{ isSmallContainer: boolean }>('div')(({ isSmallContainer }) => ({ padding: isSmallContainer ? 12 : '16px 32px', display: 'flex', alignItems: 'center', }));
关键说明
styled.withConfig()会返回一个新的styled工厂,这个工厂继承了原始styled的所有组件方法(.div、.button等),同时预应用了你的配置。- 不能在
.div<泛型>之后链式调用.withConfig(),因为TypeScript不允许在泛型实例化后的表达式后直接访问属性。 - 当前稳定版本的styled-components已移除
styled('div', config)的双参数写法,必须通过.withConfig()来传递配置。
内容的提问来源于stack exchange,提问作者Alien
相关产品推荐
相关产品推荐

