面试题答案
一键面试- 定义卡片组件的
props
类型:- 首先,我们定义卡片组件接受的
props
类型。假设卡片有一个isActive
属性来表示是否处于激活状态,以及一个textColor
属性来指定文本颜色。
type CardProps = { isActive: boolean; textColor: string; };
- 首先,我们定义卡片组件接受的
- 使用
styled - components
(以styled - components
库为例)结合TypeScript
推导样式类型:- 安装
styled - components
库,如果还未安装:npm install styled - components @types/styled - components
。 - 导入相关模块并定义卡片样式。
import styled, { css } from'styled - components'; const Card = styled.div<CardProps>` background - color: white; border: 1px solid gray; border - radius: 4px; padding: 16px; cursor: pointer; ${({ isActive }) => isActive && css` background - color: lightblue; `} &:hover { background - color: lightgray; } color: ${({ textColor }) => textColor}; `;
- 在上述代码中:
- 我们使用
styled.div<CardProps>
来表明这个样式化的div
组件接受CardProps
类型的props
。 - 通过
({ isActive }) => isActive && css
这种语法,根据isActive
属性动态地添加激活状态的样式。这里css
函数是styled - components
提供的用于编写CSS代码块的工具。 &:hover
部分定义了鼠标悬停时的样式,这是常规的CSS伪类写法。color: ${({ textColor }) => textColor}
根据传入的textColor
属性设置文本颜色。
- 我们使用
- 安装
- 在组件中使用:
import React from'react'; const App: React.FC = () => { return ( <Card isActive={true} textColor="blue"> This is a card. </Card> ); }; export default App;
- 在
App
组件中,我们将isActive
设为true
,textColor
设为blue
,并将内容放入Card
组件中。由于TypeScript
的类型推导,当我们传入不符合CardProps
类型的props
时,会在编译时收到类型错误提示,从而确保了类型安全。
- 在
这样,通过上述步骤,在复杂的CSS - in - JS场景中,基于组件的props
自动推导样式类型,保证了类型安全。