Ker*_*men 12 javascript typescript reactjs styled-components
我正在使用样式系统,库的一个关键是使用速记道具来实现简单快速的主题化。
我已经简化了我的组件,但这里是有趣的部分:
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} />
}
Run Code Online (Sandbox Code Playgroud)
我在color道具上有一个错误,上面写着:
输入'字符串| (string | null)[] | undefined' 不能分配给类型 'string | (string & (string | null)[]) | 不明确的'。
我认为这是因为styled-system使用与本机 HTML 属性相同的命名color并且它冲突。
我该如何解决这个问题?
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;
Run Code Online (Sandbox Code Playgroud)
// some-implementation.js
import Box from '.';
const Page = () => (
<Box textColor={['red', 'green']}>Content in a box</Box>
);
Run Code Online (Sandbox Code Playgroud)
小智 1
不要使用ColorProps,而是尝试使用color: CSS.ColorProperty(`import * as CSS from 'csstype'); 以下要点显示了我如何使用 typescript/styled-system 创建一些类型化的“Box”原语:https://gist.github.com/chiplay/d10435c0962ec62906319e12790104d1
祝你好运!
| 归档时间: |
|
| 查看次数: |
3602 次 |
| 最近记录: |