【问题标题】:With JavaScript + React, how to have a string evaluate inline?使用 JavaScript + React,如何让字符串内联计算?
【发布时间】:2018-04-14 20:47:59
【问题描述】:

以下功能在我的功能中非常有用:

console.log(theme.colors.blues[1]);

我正在尝试使最后一部分像这样动态:

const getColor = (theme, passedColorProp) => {
  console.log(theme.colors.[passedColorProp]);
};

getColor("blues[1]");

这是目前的错误:

模块构建失败:SyntaxError: Unexpected token (15:27)**

我怎样才能做到这一点?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    您快到了,您可以完全按照您的操作方式动态访问属性,除非您不需要额外的点。

    const getColor = (theme, passedColorProp) => {
      console.log(theme.colors[passedColorProp]);
    };
    

    请注意,这适用于 SINGLE 属性,但您不能像在示例中那样嵌套它,因为您需要使用两个不同的变量:

    const getColor = (theme, passedColorProp, id) => {
      console.log(theme.colors[passedColorProp][id]);
    };
    
    const theme = { colors: { blues: ['something', 'something else'] } };
    
    getColor(theme, 'blues', 1); // 'something else'
    

    【讨论】:

    • 有没有办法我仍然可以通过“blues[1]”然后使用 getColor 来确定这两个属性?
    • 正如 Ori Drori 所说,您必须使用正则表达式或字符串拆分来提取键并一次循环遍历属性。
    【解决方案2】:

    使用String.match() 和正则表达式提取键,然后使用Array.reduce() 迭代它们以获取值:

    const theme = {
      colors: {
        blues: ['blue0', 'blue1']
      }
    };
    
    const getColor = (theme, passedColorProp) => {
      const keys = passedColorProp.match(/[^\[\].]+/g); // match a sequence of everything but [ ] or .
      
      return keys.reduce((r, k) => r[k], theme);
    };
    
    console.log(getColor(theme, 'colors.blues[1]'));

    【讨论】:

    • 谢谢,但这是错误的Cannot read property '1' of undefined
    • 如果theme.colors.blues 返回undefined,就会发生这种情况。如您所见,它在 sn-p 中有效。
    猜你喜欢
    • 1970-01-01
    • 2016-08-05
    • 1970-01-01
    • 2020-11-15
    • 2018-11-18
    • 1970-01-01
    • 2019-11-14
    • 1970-01-01
    • 2012-01-19
    相关资源
    最近更新 更多