如何创建支持Theme访问的styled-components自定义工具higherStyled
解决方案
你的问题出在当前实现没有让styled-components的模板标签机制正确处理依赖theme的插值函数,直接传递style参数切断了theme的上下文传递。可以通过模仿styled-components原生API的写法,让higherStyled返回一个能处理模板字符串的标签函数,自动将样式包裹在&&&中,同时保留theme的访问能力。
修正后的实现
import styled from 'styled-components'; const higherStyled = (Component) => { return (...styleParts) => { // 将用户传入的样式包裹在&&& {}中,交给styled-components处理 const wrappedStyle = [`&&& {`, ...styleParts, `}`]; return styled(Component)(...wrappedStyle); }; };
使用方式
和原生styled的用法完全一致,依赖theme的插值函数可以正常访问主题:
const StyledButton = higherStyled(Button)` color: ${({ theme }) => theme.colors.myColor}; padding: 12px 24px; border-radius: ${({ theme }) => theme.radius.small}; `;
原理说明
这个实现的核心是复用了styled-components的原生模板标签处理逻辑:
higherStyled(Component)返回一个函数,该函数接收用户编写的样式模板参数(字符串数组和插值函数)- 将这些参数包裹在
&&& {}中,再传递给styled(Component)处理 - 这样styled-components会正常解析所有插值函数,包括依赖
theme的部分,自然就能访问到主题上下文
内容的提问来源于stack exchange,提问作者nwerigbxb
相关产品推荐
相关产品推荐

