问题
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, e.g.
const PasswordsMatchMessage = styled.div`
background: ${isMatchingFn};
`
回答1:
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.
来源:https://stackoverflow.com/questions/41968106/defining-a-function-inside-a-template-literal