【发布时间】:2018-06-19 09:48:31
【问题描述】:
我遵循样式组件 docs 关于 TypeScript 和 React 无状态组件,但是在创建样式组件时,我的 props 中仍然出现类型检查错误。
这是我的组件代码:
import { StatelessComponent } from 'react'
import styled, { css, keyframes } from 'styled-components'
interface IProps {
altStyle?: boolean
className?: string
name: string
type?: string
}
const PrimaryButton: StatelessComponent<IProps> = (props) =>
<button className={props.className} type={props.type}>
<span>
{props.name}
</span>
</button>
PrimaryButton.defaultProps = {
altStyle: false,
type: 'button',
}
const hoverAnimation = keyframes`
from {
opacity: 0;
} to {
opacity: 1;
}
`
const StyledPrimaryButton = styled(PrimaryButton)`
background: linear-gradient(135deg, #b60c41, #b30d41, #51213c);
border: none;
border-radius: 0;
color: #fff;
cursor: pointer;
font-size: 14px;
font-weight: 400;
height: 45px;
letter-spacing: 2px;
padding: 0 28px;
position: relative;
text-transform: uppercase;
> span {
position: relative;
}
&:before {
background: #51213c;
bottom: 0;
content: "";
left: 0;
opacity: 0;
position: absolute;
right: 0;
top: 0;
}
&:hover:before {
animation: ${hoverAnimation} 2s ease-in-out infinite alternate;
}
${(props) => props.altStyle && css`
background: transparent;
border: solid 2px #fff;
transition: background 1s ease;
&:hover {
background: #b60c41;
border: none;
padding: 0 30px;
}
&:hover:before {
animation-delay: 1s;
}
`}
`
export default StyledPrimaryButton
这是我得到的错误:
components/buttons/PrimaryButton.tsx(60,5): error TS2345: Argument of type '(props: ThemedStyledProps) => false |插值值[] | undefined' 不可分配给“插值>”类型的参数。 [0] 类型'(道具:ThemedStyledProps) => false |插值值[] | undefined' 不可分配给类型 'ReadonlyArray |插值函数...'。 [0] 类型 '(props: ThemedStyledProps) => false | 中缺少属性 'concat'插值值[] |未定义'。
如果我添加 props: any,一切都会按预期构建,但是我想找到一个更好的解决方案,以免我的组件被大量 props: any 弄乱。
关于如何进行的任何想法?
【问题讨论】:
-
您发布的代码使用最新的 react、styled-components 和 TS 编译器按预期编译(没有错误)
-
很奇怪。我也在使用上述软件包的最新版本。但是,我忽略了我正在使用 Next.js 进行服务器端渲染。也许这会引起问题?
标签: reactjs typescript styled-components