Article directory
Introduction to JSX syntax
Know JSX syntax
Let's first look at a piece of code
// 定义根组件
const element = <div>Hello World</div>
// 渲染根组件
const app = ReactDOM.createRoot(document.querySelector("#app"))
app.render(element)
What is the label syntax for the assignment on the right side of the declaration of the element variable?
It's not a string (because it's not wrapped in quotes);
It looks like an HTML element, but can we directly assign an HTML element to a variable in js?
In fact, it is not possible. If we remove type="text/babel", there will be a syntax error;
What is it? In fact, it is a piece of jsx syntax code;
What is JSX?
JSX is an
JavaScript的语法扩展
(eXtension), also called JavaScript XML in many places, because it looks like a piece of XML syntax;It is used to describe our UI interface, and its completion can be combined with JavaScript;
It is different from module syntax in Vue, you don't need to learn some directives in module syntax (such as v-for, v-if, v-else, v-bind);
So why did React choose JSX? React believes that it is inherently coupled 渲染逻辑
with otherUI逻辑
For example, UI needs to bind events (button, a native, etc.);
For example, the data status needs to be displayed in the UI;
For example, when some state changes, the UI needs to be changed;
They are inseparable, so React does not separate the markup into different files, but combines them together. This combination is 组件
(Component) ;
Of course, we will continue to learn more about components in the future;
Here, we just need to know that JSX is actually a structural syntax embedded in JavaScript;
JSX writing specification :
There can only be one root element at the top level of JSX, so we often wrap a div element in the outer layer (or use the Fragment we learn later);
In order to facilitate reading, we usually wrap a parenthesis () in the outer layer of jsx, which is convenient for reading, and jsx can be written with a newline;
Labels in JSX can be single or double;
Note: If it is a single tag, it must end with />;
Writing JSX comments
Writing comments in the JSX section can only write multi-line comments, and wrap a curly brace
render() {
const {
message } = this.state
return (
<div>
{
/* jsx的注释 */}
<h2>{
message}</h2>
</div>
)
}