You can embed any JavaScript expression in JSX by wrapping it in curly braces.
通过大括号你可以在JSX里使用嵌入任何JavaScript的表达式。
For example, 2 + 2, user.firstName, and formatName(user) are all valid expressions:
例如2+2,user.firstNam和formatName都是有效的表达式。
function formatName(user) {
return user.firstName + ' ' + user.lastName;
}
const user = {
firstName: 'Harper',
lastName: 'Perez'
};
const element = (
<h1>
Hello, {formatName(user)}!
</h1>
);
ReactDOM.render(
element,
document.getElementById('root')
);
Try it on CodePen.
试着把它放到CodePen里。
We split JSX over multiple lines for readability. While it isn't required, when doing this, we also recommend wrapping it in parentheses to avoid the pitfalls of automatic semicolon insertion.
我们将JSX拆分为多行以提高可读性。虽然不是必需的,但当执行此操作时,我们还建议将其括在括号中,以避免自动分号插入的陷阱。