在使用 styled-components
时,如果你遇到模板字符串中的变量返回 undefined
的问题,通常是因为变量作用域或导入导出的问题
首先,确保你使用的变量已经正确导入到组件文件中。例如:
// variables.js
export const primaryColor = '#3498db';
// MyComponent.js
import styled from 'styled-components';
import { primaryColor } from './variables';
const StyledDiv = styled.div`
color: ${primaryColor};
`;
确保变量在模板字符串的作用域内是可访问的。例如:
// MyComponent.js
import styled from 'styled-components';
const primaryColor = '#3498db';
const StyledDiv = styled.div`
color: ${primaryColor};
`;
如果你需要在多个组件中使用相同的样式变量,可以考虑使用函数来传递变量:
// variables.js
export const getPrimaryColor = () => '#3498db';
// MyComponent.js
import styled from 'styled-components';
import { getPrimaryColor } from './variables';
const StyledDiv = styled.div`
color: ${getPrimaryColor()};
`;
另一种方法是使用 CSS 变量(自定义属性),这样可以在全局范围内定义样式变量:
// global.css
:root {
--primary-color: #3498db;
}
// MyComponent.js
import styled from 'styled-components';
import './global.css';
const StyledDiv = styled.div`
color: var(--primary-color);
`;
确保变量名拼写正确,避免因为拼写错误导致变量未定义。
以下是一个完整的示例,展示了如何正确使用 styled-components
和样式变量:
// variables.js
export const primaryColor = '#3498db';
// MyComponent.js
import React from 'react';
import styled from 'styled-components';
import { primaryColor } from './variables';
const StyledDiv = styled.div`
color: ${primaryColor};
font-size: 16px;
padding: 10px;
`;
const MyComponent = () => {
return (
<div>
<StyledDiv>Hello, World!</StyledIdv>
</div>
);
};
export default MyComponent;
通过以上方法,你应该能够解决 styled-components
模板文字返回 undefined
的问题。如果问题仍然存在,请检查是否有其他潜在的问题,例如模块导入导出错误等。
领取专属 10元无门槛券
手把手带您无忧上云