don*_*zul 9 typescript styled-components
如果我有以下带有 defaultProp 的按钮
export interface IButton {
variant: 'action' | 'secondary';
}
export const Button = styled('button')<IButton>`
background-color: #fff;
${props =>
props.variant === 'action' &&
css`
color: blue;
`};
${props =>
props.variant === 'secondary' &&
css`
color: gray;
`};
`;
Button.defaultProps = {
variant: 'action',
};
Run Code Online (Sandbox Code Playgroud)
有办法打字吗?当尝试使用它时
<Button>Hello</Button>
Run Code Online (Sandbox Code Playgroud)
Typescript 抱怨没有传递变量,有没有办法使用样式组件输入 defaultProps?
问题是 TypeScript 3.0 对检查 JSX 元素的支持需要在组件上声明defaultProps的类型。defaultProps改变defaultProps现有组件的 是行不通的,而且我不知道有什么好方法可以defaultProps在由诸如 之类的函数生成的组件上声明styled。(在某种程度上,这是有道理的:库创建了一个组件并且不希望您修改它。也许库甚至defaultProps出于某些内部目的而设置自己。)kingdaro 的解决方案很好,或者您可以使用包装器组件:
const Button1 = styled('button')<IButton>`
background-color: #fff;
${props =>
props.variant === 'action' &&
css`
color: blue;
`};
${props =>
props.variant === 'secondary' &&
css`
color: gray;
`};
`;
export class Button extends React.Component<IButton> {
static defaultProps = {
variant: 'action'
};
render() {
return <Button1 {...this.props}/>;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21008 次 |
| 最近记录: |