我想创建一个动态函数,从字符串中返回一个变量。我正在使用 ES6 中的模板字符串,但我不知道以后如何调用它。我需要传递一个将对象作为引用的变量。
const checkDeviceWidth = type => {
if (documentWidth > 1200) return `${type}Options`;
if (documentWidth > 414) return `${type}MediumOptions`;
return `${type}MobileOptions`;
};
...
<Lottie
ref={backgroundImg}
isClickToPauseDisabled={true}
speed={1}
options={checkDeviceWidth('background')}></Lottie>
根据参数返回对象
const backgroundOptions = {
loop: true,
autoplay: true,
animationData: background.default,
};
const backgroundMediumOptions = {
loop: true,
autoplay: true,
animationData: backgroundMedium.default,
};
有了这个,我得到一个错误,在选项中我必须传递一个对象而不是一个字符串。如果没有 eval()
函数,以后如何调用它?我正在使用 React
最佳答案
你可以把你的常量放到对象中
const myObject = {
backgroundOptions: {
loop: true,
autoplay: true,
animationData: background.default
},
backgroundMediumOptions: {
loop: true,
autoplay: true,
animationData: backgroundMedium.default
}
};
然后得到正确的属性
const checkDeviceWidth = type => {
if (documentWidth > 1200) return myObject[`${type}Options`];
if (documentWidth > 414) return myObject[`${type}MediumOptions`];
return myObject[`${type}MobileOptions`];
};
关于javascript - 如何在js中从字符串构建变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58691150/