在Codepen React项目中使用@emotion/styled页面空白,求助解决
问题排查:@emotion/styled 导致React页面空白
问题描述
我在Codepen的React项目里用@emotion/styled改造Button组件,想通过props传递背景色和文字颜色,让按钮和应用其他部分颜色同步。但替换组件后页面直接空白,求解决。
错误代码片段
import EmotionStyled from "https://cdn.skypack.dev/@emotion/styled@11.10.5"; import styled from "https://cdn.skypack.dev/@emotion/styled@11.10.5" function Button(props) { const Button = styled.button` margin-top: 2rem; background-color: ${props.colorChange}; color: white; border: none; height: 2.5rem; border-radius: 4px; padding: 0 1rem; font-size: 1rem; &:nth-of-type(1) { margin-right: 0.5rem; } &:hover { background-color: ${props.colorChange}; opacity: 0.9; } ` return ( <div className='buttons'> <div className='left'> <Button><a id='tweet-quote' target='_blank' rel='noreferrer'><i className="fa-brands fa-twitter"></i></a></Button> <Button><a id='tumblr-quote' target='_blank' rel='noreferrer'><i className="fa-brands fa-tumblr"></i></a></Button> </div> <Button id='new-quote' onClick={props.handleChange}>New quote</Button> </div> ) }
错误原因分析
- 命名冲突:外层函数组件叫
Button,内部又定义了同名的styled组件Button,变量作用域混乱导致React无法正确识别组件。 - styled组件定义位置错误:把styled组件放在函数内部,每次组件渲染都会重新创建这个组件,触发不必要的重渲染甚至渲染异常。
- props传递方式错误:在styled模板字符串里直接用
props.colorChange是错误的,必须通过函数参数来获取组件props。
修复后的代码
// 只保留必要的styled导入 import styled from "https://cdn.skypack.dev/@emotion/styled@11.10.5"; // 将styled组件定义在函数外部,避免重复创建 const StyledButton = styled.button` margin-top: 2rem; background-color: ${props => props.colorChange}; color: white; border: none; height: 2.5rem; border-radius: 4px; padding: 0 1rem; font-size: 1rem; &:nth-of-type(1) { margin-right: 0.5rem; } &:hover { background-color: ${props => props.colorChange}; opacity: 0.9; } `; function Button(props) { return ( <div className='buttons'> <div className='left'> <StyledButton colorChange={props.colorChange}> <a id='tweet-quote' target='_blank' rel='noreferrer'> <i className="fa-brands fa-twitter"></i> </a> </StyledButton> <StyledButton colorChange={props.colorChange}> <a id='tumblr-quote' target='_blank' rel='noreferrer'> <i className="fa-brands fa-tumblr"></i> </a> </StyledButton> </div> <StyledButton id='new-quote' onClick={props.handleChange} colorChange={props.colorChange} > New quote </StyledButton> </div> ) }
关键修改点
- 删掉多余的
EmotionStyled导入,只保留styled。 - 把styled组件改名为
StyledButton,避免和外层函数组件重名。 - 将
StyledButton移到函数组件外部,防止每次渲染重复创建。 - 模板字符串中用
props => props.colorChange来接收props。 - 给所有
StyledButton都传递colorChangeprops,保证按钮都能正确获取颜色值。
内容的提问来源于stack exchange,提问作者annie
相关产品推荐
相关产品推荐

