如何在@emotion/react/TypeScript中为样式对象添加条件props?

在@emotion/react中通过props控制CSS样式有两种主流实现方式,直接使用官方原生API即可实现,不需要额外依赖:
方法1:使用css prop接收函数返回样式
首先确保文件顶部配置了emotion的jsx解析标识,否则css prop不会生效:
/** @jsxImportSource @emotion/react */
之后给元素的css属性传入样式对象或者模板字符串,直接读取当前组件接收的自定义props,根据props值返回对应的样式规则即可:
/** @jsxImportSource @emotion/react */ function StatusTag({ type = 'default', children }) { return ( <span css={{ padding: '2px 8px', borderRadius: 4, fontSize: 12, // 根据传入的type prop动态返回对应颜色 backgroundColor: type === 'success' ? '#f6ffed' : type === 'error' ? '#fff2f0' : '#f5f5f5', color: type === 'success' ? '#52c41a' : type === 'error' ? '#ff4d4f' : '#666' }} > {children} </span> ) } // 使用时直接传入控制样式的props即可 // <StatusTag type="success">审核通过</StatusTag> // <StatusTag type="error">审核驳回</StatusTag>
方法2:使用styled API封装动态样式组件
如果需要复用动态样式组件,推荐用@emotion/styled提供的API,定义样式时可以直接读取组件传入的props生成对应样式:
import styled from '@emotion/styled' const CustomButton = styled.button` padding: 8px 16px; border-radius: 4px; border: none; cursor: pointer; /* 根据props动态设置按钮样式 */ background: ${props => props.variant === 'primary' ? '#1677ff' : '#fff'}; color: ${props => props.variant === 'primary' ? '#fff' : '#333'}; border: 1px solid ${props => props.variant === 'primary' ? '#1677ff' : '#d9d9d9'}; &:hover { opacity: 0.8; } ` // 使用 // <CustomButton variant="primary">提交</CustomButton> // <CustomButton>取消</CustomButton>
如果使用TypeScript,只需要给styled组件声明对应的props类型即可获得类型校验,避免属性写错:
import styled from '@emotion/styled' type CustomButtonProps = { variant?: 'primary' | 'default'; size?: 'small' | 'middle' | 'large'; } const CustomButton = styled.button<CustomButtonProps>` /* 样式中可以安全读取size、variant属性,TS会自动做类型校验 */ padding: ${props => props.size === 'small' ? '4px 8px' : props.size === 'large' ? '12px 24px' : '8px 16px'}; /* 其余样式和上面一致 */ `
内容的提问来源于stack exchange,提问作者React-beginner
相关产品推荐
相关产品推荐

