如何拼接变量名?实现MakeMargin函数返回theme.spacing.unit1变量
解决方法:用对象动态属性访问语法
嘿,我懂你的需求啦——你希望调用MakeMargin(unit1)时,能直接返回theme.spacing.unit1这个属性值,而不是把对象和参数拼出奇怪的字符串对吧?
你之前的代码问题在于,theme.spacing是一个对象,当你用+把它和props拼接时,JS会自动把对象转换成字符串(通常是[object Object]),最后得到的是类似[object Object]unit1的无效结果,这肯定不是你想要的。
要实现动态访问对象的属性,你需要用方括号语法,而不是点语法(点语法只能用固定的属性名称)。正确的写法应该是这样:
function MakeMargin(props) { // 用方括号访问theme.spacing的动态属性 return theme.spacing[props]; }
额外注意:确保theme可访问
如果是在Material-UI项目中,你需要确保theme变量在函数作用域内是可用的。通常我们会用useTheme钩子来获取主题对象:
import { useTheme } from '@mui/material/styles'; function MakeMargin(props) { const theme = useTheme(); return theme.spacing[props]; }
调用方式
当你需要获取theme.spacing.unit1时,要传入对应的属性名字符串:
// 直接传字符串 const myMargin = MakeMargin('unit1'); // 或者先定义变量再传 const unit1 = 'unit1'; const myMargin = MakeMargin(unit1);
这样就能准确返回theme.spacing.unit1的属性值啦!
内容的提问来源于stack exchange,提问作者Romainpetit
相关产品推荐
相关产品推荐

