小编典典

在模板文字中定义函数

reactjs

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

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

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

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

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

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

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

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

阅读 253

收藏
2020-07-22

共1个答案

小编典典

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

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',表示每次都在创建一个新函数。

与此版本进行比较:

trackInterpolations`background: ${isMatchingFn};`

第一次运行时,它将求值为'Got a different function'(因为还没有看到isMatchingFn),但是如果再评估几次,它将始终得到'Got the same function',因为函数引用正在被重用。

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

2020-07-22