我正在使用式样系统,库的关键之一是使用速记道具,以方便和快速地进行主题化。
我简化了组件,但这里有一个有趣的部分:
import React from 'react'
import styled from 'styled-components'
import { color, ColorProps } from 'styled-system'
const StyledDiv = styled('div')<ColorProps>`
${color}
`
const Text = ({ color }: ColorProps) => {
return <StyledDiv color={color} />
}我在color道具上有一个错误,上面写着:
类型'string not (string可比null)[] \\ undefined‘不能分配到'string not (string & (string _Null)[]\x\ undefined’。
我认为这是因为styled-system使用了与原生color属性相同的命名,并且与之冲突。
我该怎么解决这个问题?
发布于 2019-04-12 13:54:39
color似乎是在react的声明文件HTMLAttributes下声明的-它不是导出的。
我不得不通过创建一个定制道具来解决这个问题
示例使用的是@emotion/styled,但也使用styled-components。
// component.js
import styled from '@emotion/styled';
import { style, ResponsiveValue } from 'styled-system';
import CSS from 'csstype';
const textColor = style({
prop: 'textColor',
cssProperty: 'color',
key: 'colors'
});
type Props = {
textColor?: ResponsiveValue<CSS.ColorProperty>
}
const Box = styled.div<Props>`
${textColor};
`
export default Box;// some-implementation.js
import Box from '.';
const Page = () => (
<Box textColor={['red', 'green']}>Content in a box</Box>
);发布于 2019-01-12 16:51:50
不要使用ColorProps,尝试使用color: CSS.ColorProperty (从‘csstype’导入*为CSS );下面是说明我如何创建带有类型记录/样式系统的类型化"Box“原语的要点:https://gist.github.com/chiplay/d10435c0962ec62906319e12790104d1
祝好运!
发布于 2022-06-01 01:32:54
这似乎只有在您将支持从祖先/父组件传递到自定义组件而不是直接传递到“样式”组件时才会发生。我在样式-组件GitHub问题上找到了一个关于它的讨论。在后面的线程中,讨论了如何使用瞬态道具及其在造型-部件v5.1中的最终包含。
然而,在我的情况下,这似乎并没有完全解决问题。
这个问题似乎是由于所讨论的组件返回HTML元素,因此它被正确地扩展(由React.HTMLAttributes)包括color: string | undefined作为该元素的DOM属性。当然,这与ColorProps不兼容,因此出现了错误。样式-组件过滤掉一个包括color的白名单,但是这不会发生在您的自定义或临时的。
这可以通过多种方式解决,但最干净的似乎是将as?: React.ElementType添加到您的类型定义中。
在这种情况下:
import React from 'react'
import styled from 'styled-components'
import { color, ColorProps } from 'styled-system'
interface Props extends ColorProps { as?: React.ElementType }
const StyledDiv = styled('div')<Props>`
${color}
`
const Text = ({ color }: Props) => {
return <StyledDiv color={color} />
}这样,React.HTMLAttributes的扩展将被React.ElementType所取代,因此不再与color DOM属性发生冲突。
这也解决了传递SpaceProps的问题。
https://stackoverflow.com/questions/53711454
复制相似问题