在模板文字中定义函数 [英] Defining a function inside a template literal

查看:77
本文介绍了在模板文字中定义函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using styled-components as a solution to styling for React. They've got a nice approach that uses template literals to interpolate CSS. The template literals are passed the component's props so that you can do things like:

const PasswordsMatchMessage = styled.div`
    background: ${props => props.isMatching ? 'green' : 'red'};
`

结果是一个组件,该组件根据isMatching的值呈现带有绿色或红色背景的div标签.上面将通过JSX像这样使用:

The result is a component that renders a div tag with either a green or red background depending on the value of isMatching. The above would be used via JSX like this:

<PasswordsMatchMessage isMatching={doPasswordsMatch}>...</PasswordsMatchMessage>

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

Every time the value of props changes, this string is going to be re-interpolated. Which finally brings me to my question:

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

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

If so, then I may consider creating functions outside the template literal and just passing those in, e.g.

const PasswordsMatchMessage = styled.div`
    background: ${isMatchingFn};
`

推荐答案

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

Yes, it would define a new version of the function each time the template literal is interpolated. You can verify that by defining your own tag that keeps track of the previous value.

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

然后运行

trackInterpolations`background: ${props => props.isMatching ? 'green' : 'red'};`

几次,并注意到它总是计算为'Got a different function',表明它每次都在创建一个新函数.

a couple of times and notice that it always evaluates to 'Got a different function', indicating that it's creating a new function each time.

将此与该版本进行比较:

Compare that to this version:

trackInterpolations`background: ${isMatchingFn};`

第一次运行时,它将评估为'Got a different function'(因为尚未看到isMatchingFn),但是如果再评估几次,它将始终导致'Got the same function',因为函数引用正在重用.

The first time it's run, it will evaluate to 'Got a different function' (because it hasn't seen the isMatchingFn yet), but if you evaluate it a few more times it will always result in 'Got the same function', because the function reference is being reused.

在这种情况下,我不会太担心性能的影响,并且选择可读性更高的内容,除非您真正注意到速度变慢.与重新渲染div相比,创建新函数的开销可能不会很高.

I wouldn't worry too much about the performance impact though in this case, and go with whatever is more readable unless you actually notice a slowdown. Compared to re-rendering the div, the overhead of creating a new function isn't likely to be very high.

这篇关于在模板文字中定义函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆