在模板文字中定义函数

max*_*son 3 javascript ecmascript-6 reactjs template-literals styled-components

我正在使用样式组件作为React样式的解决方案.他们有一个很好的方法,使用模板文字插入CSS.模板文字传递组件的道具,以便您可以执行以下操作:

const PasswordsMatchMessage = styled.div`
    background: ${props => props.isMatching ? 'green' : 'red'};
`
Run Code Online (Sandbox Code Playgroud)

结果是一个组件,它div根据值的值呈现带有绿色或红色背景的标记isMatching.以上将通过JSX使用,如下所示:

<PasswordsMatchMessage isMatching={doPasswordsMatch}>...</PasswordsMatchMessage>
Run Code Online (Sandbox Code Playgroud)

每次props更改值时,都会重新插入此字符串.这终于让我想到了我的问题:

每次插入模板文字时,是否都会重新定义模板文字中定义的箭头函数?

如果是这样,那么我可以考虑在模板文字之外创建函数,并将其传递给,例如

const PasswordsMatchMessage = styled.div`
    background: ${isMatchingFn};
`
Run Code Online (Sandbox Code Playgroud)

Mat*_*ley 5

是的,每次插入模板文字时,它都会定义一个新版本的函数.您可以通过定义自己的跟踪先前值的标记来验证.

var previous;
function trackInterpolations(literalParts, interpolated) {
  if (interpolated === previous) {
    answer = 'Got the same function';
  } else {
    answer = 'Got a different function';
  }
  previous = interpolated;
  return answer;
}
Run Code Online (Sandbox Code Playgroud)

然后跑

trackInterpolations`background: ${props => props.isMatching ? 'green' : 'red'};`
Run Code Online (Sandbox Code Playgroud)

几次,并注意到它总是评估'Got a different function',表明它每次都在创建一个新的功能.

与此版本相比:

trackInterpolations`background: ${isMatchingFn};`
Run Code Online (Sandbox Code Playgroud)

它第一次运行时,它将评估为'Got a different function'(因为它还没有看到isMatchingFn),但如果你再评估它几次,它将总是导致'Got the same function',因为函数引用正被重用.

在这种情况下,我不会过分担心性能影响,除非你真的注意到减速,否则请使用更具可读性的东西.与重新渲染div相比,创建新函数的开销不太可能很高.