反应,使用模板文字将值从if语句传递给const

时间:2018-11-26 22:11:39

标签: javascript reactjs typescript

我有一个导出的const,它带有两个参数。使用这两个参数,我想进行一些检查,并在命中后将结果设置为变量。

在该导出的const中,我还有一个带有模板字符串的const,这是我要添加先前if语句的结果的位置。像这样:

export const getTest = (typeX, typeY) => {

     let testing = '';
     if (typeX === 'x' && typeY === 'y') {
         testing = 'y';
     }

     const testFormat = `
     <div style='
      color: white;
      font-size: 1rem;
      font-weight: bold;
      background: {series.color};'
      >
      {point.y}
     </div>
    `;

    return {
     headerFormat: '',
     testFormat,
     useHTML: true,
     padding: 0,
    };
};

testFormat中,我有 {point.y} ,它可以从所在位置正常运行,但是我应该如何进行测试(从if语句)旁边?

{testing} {point.y}

1 个答案:

答案 0 :(得分:0)

此问题的解决方案是将${testing}插入testFormat的模板字符串中,如下所示:

const testFormat = `
 <div style='
  color: white;
  font-size: 1rem;
  font-weight: bold;
  background: {series.color};'
  >
  ${testing} {point.y}
 </div>
`;

通过将${testing}添加到您的字符串中,这将导致变量testing的值在此时插入模板字符串中,成为testFormat的结果字符串值。