简体   繁体   中英

Defining a function inside a template literal

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'};
`

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>

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

Does the arrow function defined inside the template literal get re-defined every time the template literal is interpolated?

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

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;
}

Then run

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

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};`

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM