面试题答案
一键面试- 首先安装
@types/styled - components
以获取类型声明支持。 - 定义按钮样式对象类型示例:
import styled from'styled - components';
// 定义按钮样式对象的类型
type ButtonStyleProps = {
primary?: boolean;
disabled?: boolean;
};
// 使用类型定义样式对象
const StyledButton = styled.button<ButtonStyleProps>`
background - color: ${props => props.primary? 'blue' : 'gray'};
color: white;
border: none;
padding: 10px 20px;
border - radius: 5px;
cursor: ${props => props.disabled? 'not - allowed' : 'pointer'};
opacity: ${props => props.disabled? 0.5 : 1};
`;
在上述代码中:
- 定义了
ButtonStyleProps
类型接口,用于描述按钮样式对象可能接收的属性,这里假设按钮有primary
(是否为主按钮)和disabled
(是否禁用)两个属性。 - 在创建
StyledButton
时,将ButtonStyleProps
作为泛型参数传递给styled.button
,这样在样式模板字符串中就可以安全地使用props
的这些属性来设置样式,实现了类型安全的CSS - in - JS方案。