@emotion/react:forwardRef结合Composition时类名不匹配问题求助
问题描述
当前代码可正常运行,但存在类名不匹配问题,使用的@emotion/react版本为11.10.4。不使用Composition(数组语法)时该问题可解决,但将forwardRef包裹的组件与Composition结合使用会出现类名不匹配,现寻求解决方案。
代码示例:
const Home: NextPage = () => { return ( <div css={[ css` display: flex; `, ]} > <RefComponent /> </div> ); }; const RefComponent = forwardRef<any, any>((props, ref) => { return ( <h1 ref={ref} css={[ css` color: red; `, ]} > Hello </h1> ); });
解决方案
方案1:改用Styled组件创建带ref的样式组件
用@emotion/styled构建样式化组件,再结合forwardRef,能确保样式类名被正确生成和关联:
import styled from '@emotion/styled'; const StyledHeading = styled.h1` color: red; `; const RefComponent = forwardRef<any, any>((props, ref) => { return <StyledHeading ref={ref} {...props}>Hello</StyledHeading>; });
方案2:显式处理样式数组
在forwardRef组件内部,将样式数组通过css函数显式包裹,让Emotion正确编译样式:
const RefComponent = forwardRef<any, any>((props, ref) => { const headingStyles = css([ css` color: red; `, ]); return ( <h1 ref={ref} css={headingStyles}> Hello </h1> ); });
方案3:升级Emotion版本
该问题可能是11.10.4版本的特定bug,尝试升级@emotion/react到最新稳定版,大概率能修复类名不匹配问题。
内容的提问来源于stack exchange,提问作者555jiki
相关产品推荐
相关产品推荐

