无法获取函数内部变量的值 [英] Unable to get the value of variable inside a function
问题描述
基于注释,我更改了代码. 我得到了代码有什么问题.我想知道如何使它工作?
EDIT 1: Based on the comments I have changed the code. EDIT 2: I get what is wrong with the code. What I want to know if how can I make it work?
我想创建一个通用函数来生成如下所示的样式. 这是在ES6中.
I want to create a generic function to generate styles as given below. This is in ES6.
const PADDING = [0, 1, 2, 3, 4];
const MARGIN = [0, 8, 16 ];
const generateStyle = (type) => {
const styles = {};
const upperCase = type.toUpperCase();
upperCase.forEach((item) => {
styles[`${type}-${item}`] = {
[type]: `${item}px !important`,
};
});
return styles;
};
generateStyle('padding');
此代码给出以下错误:"TypeError:upperCase.forEach不是一个函数.当我记录大写字母时,其值为'PADDING'.
This code gives the following error: "TypeError: upperCase.forEach is not a function. When I log the uppercase, its value is 'PADDING'.
但是当我硬编码PADDING而不是大写时,它就可以正常工作.
But when I hardcode PADDING instead of uppercase, it works fine.
我在做什么错了?
如何使函数通用,以便我也可以使用generateStyle('margin').
How to make the function generic so that I can use generateStyle('margin') as well.
推荐答案
这应该有效:
const PADDING = [0, 1, 2, 3, 4];
const MARGIN = [0, 8, 16 ];
const generateStyles = (array, type) => {
if(array && array.length) {
let styles = {};
array.forEach(item => {
styles[`${type}-${item}`] = {
[type]: `${item}px !important`
}
})
return styles
}
}
console.log(generateStyles(PADDING, "padding"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
您需要做的就是传递一个值数组(PADDING)和一个CSS属性名称("padding").
All you need to do is pass an array of values (PADDING) and a css property name ("padding").
希望有帮助!
这篇关于无法获取函数内部变量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!