const element = <h1>hello, world</h1>
javascript的一种扩展语法
const name = 'josh perez';
const element = <h1>hello,{name}</h1> //用花括号把havascript表达式嵌入到JSX中
ReactDOM.render(
element,
document.getElementById('root')
);
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')
);
编译之后,jsx表达式变成了常规的javascript对象,可以再if语句或者for循环中使用jsx
function getGreeting(user) {
if(user) {
return <h1>hello,{formatName(user)}!</h1>;
}
return <h1>hello, stranger</h1>;
}
用JSX指定子元素,如果是空标签应该立即闭合它
const element = <img src={user.avatarUrl} />;
Babel将JSX编译成React.createElement()
调用
const element = (
<h1 className="greeting">hello,world</h1>
);
const element = React.createElement(
'h1',
{className:'greeting'},
'hello,world'
);