【问题标题】:How to use template literal on a function paremeter? [duplicate]如何在函数参数中使用模板文字? [复制]
【发布时间】:2019-09-12 01:18:34
【问题描述】:

我正在尝试连接一个字符串来塑造一个对象,如下所示:

{addInput.inputs.map((input, index) => (
  <FormField
    key={input}
    label="Entreprenuer Name*"
    controlId={`entreprenuerName-${index}`}
    onChange={e => {
      startupFourthStepFormActionHandler({ `entreprenuerName-${index}`: e.target.value });
    }}
    value={startupFourthStepForm.entreprenuerName}
  />
))}

但我在此行收到 Failed To Compiled 错误和 Property assignment expected

onChange={e => {
      startupFourthStepFormActionHandler({ `entreprenuerName-${index}`: e.target.value })
};

我想要的只是将index 添加到对象上的entreprenuerName- 键。

我错过了什么?

【问题讨论】:

    标签: javascript reactjs ecmascript-6


    【解决方案1】:

    您需要将 template literal 括在方括号 [...] 中,以执行您要执行的操作。这是computed property names的使用方式,例如:

    let index = 1;
    
    const obj = {
       [`entreprenuerName-${index}`]: "some_value"
    };
    
    index = 2;
    obj[`entreprenuerName-${index}`] = "some_other_value";
    
    console.log(obj);
    .as-console {background-color:black !important; color:lime;}
    .as-console-wrapper {max-height:100% !important; top:0;}

    或者,在您的特定情况下,将代码更改为:

    {addInput.inputs.map((input, index) => (
        <FormField
            key={input}
            label="Entreprenuer Name*"
            controlId={`entreprenuerName-${index}`}
            onChange={e => {
                startupFourthStepFormActionHandler({
                    [`entreprenuerName-${index}`]: e.target.value
                });
            }}
            value={startupFourthStepForm.entreprenuerName}
        />
    ))}
    

    【讨论】:

      【解决方案2】:

      计算对象键需要包装在[] 中。试试这个:

        startupFourthStepFormActionHandler({ [`entreprenuerName-${index}`]: e.target.value });
      

      【讨论】:

        猜你喜欢
        • 2023-03-12
        • 2019-12-17
        • 2022-01-01
        • 2017-01-18
        • 2013-07-27
        • 1970-01-01
        • 2022-01-24
        • 1970-01-01
        • 2019-12-24
        相关资源
        最近更新 更多