我遵循了样式组件 docs关于 TypeScript 和 React 无状态组件,但是在创建样式化组件时,我的 Prop 中仍然出现类型检查错误。
这是我的组件代码:
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 | InterpolationValue[] | undefined' is not assignable to parameter of type 'Interpolation>'. [0] Type '(props: ThemedStyledProps) => false | InterpolationValue[] | undefined' is not assignable to type 'ReadonlyArray | InterpolationFunct...'. [0] Property 'concat' is missing in type '(props: ThemedStyledProps) => false | InterpolationValue[] | undefined'.
如果我添加 props: any
,一切都按预期构建,但是我想找到一个更好的解决方案,以免我的组件因大量 props: any
而变得困惑。 .
关于如何进行的任何想法?
最佳答案
回答我自己的问题,这是我的 tsconfig.json
文件:
{
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"jsx": "react-native",
"module": "commonjs",
"strict": true,
"target": "es5"
}
}
我设置了 "strict": false
,现在我遇到了预期的行为,省略 : any
时没有错误。其他一切正常。
关于reactjs - 类型检查无状态组件中的 styled-components Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48183785/