react documentation notes
Introduction to jsx
jsx is a javascript syntax extension, jsx is used to declare elements in React.
Using expressions in jsx
Expressions in jsx are enclosed in curly brackets. For example 2+2
, user.firstName
, formatName(user)
etc.
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')
)
When writing jsx, line breaks and indentation are generally used, which can enhance the readability of the code, and add a parenthesis outside the jsx code to prevent 分号自动插入
bugs.
jsx itself is actually an expression
After compiling, jsx is actually converted to a normal javascript object. This also means that you can use JSX in the following if
or for
statement, copy it and pass it in as a parameter, or as a return value:
function getGreeting(user){
if(user){
return <h1>hello,{formatName(user)}</h1>;
}
return <h1>hello,Stranger</h1>;
}
JSX properties
String-valued properties can be defined using quotes:
const element=<div tabIndex='0'></div>;
You can also use curly braces to define properties that take JavaScript expressions as values:
const element=<img src={user.avatarUrl}></img>;
When using javascript expressions wrapped in curly braces, don't put quotes around them. JSX will recognize the content inside the quotes as a string rather than an expression.
JSX nesting
If the Jsx tag is closed, then you need to use it at the end />
, just like XML/HTML:
const element = <img src={user.avatatUrl}/>
JSX tags can also be nested within each other:
const element = {
<div>
<h1>Hello!</h1>
<h2>Good to see you here.</h2>
</div>
}
Note: The features of JSX are closer to javascript than HTML, so ReactDOM uses camelCase to define attribute names instead of HTML attribute names.
JSX stands for Objects
Babel transforms the JSX into a React.createElement()
method call called .
The following two codes do exactly the same thing:
const element = (
<h1 class="greeting">
hello,world!
</h1>
);
const element =React.createElement(
'h1',
{className:greeting},
'hello,world!'
)
React.createElement()
This method first performs some bug-avoiding checks, and then returns an object similar to the following example:
const element = {
type:'h1',
props:{
className:'greeting',
children:'hello,world'
}
}
Such objects are called "React elements". He represents everything you see on the screen. React builds the DOM by reading these objects and keeps the content consistent.