JSX basic syntax

JSX is a syntax extension to JavaScript. It’s not a string, it’s not HTML. JSX describes the essence of UI interaction very well, and it has all the functionality of JavaScript. JSX generates React “elements”.

The basic use

\src\index.js

Import React from 'React' import ReactDom from 'React -dom' JSX const title = <h1>Hello React</h1> Incoming JSX and node object ReactDom. Render (title, document getElementById (" root "))Copy the code

When using JSX, you can simply follow the rules of HTML (keep in mind that it’s not HTML), so use parentheses () for multiple lines of code;

Import React from 'React' import ReactDom from 'React -dom' // wrap JSX with parentheses Const title = (<div> <h1>Hello React</h1> <span> </span> </div>) ReactDom.render(title,document.getElementById('root'))Copy the code

Set up the VS Code editor for JSX Code completion:

Add "emmet.includeLanguages": {"javascript": "javascriptreact"} to user SettingsCopy the code

As shown below:

JSX expression

Previously said that JSX has all the functions of JavaScript, but in the specific use can be directly applied to the rules of HTML, in other words, in the rules of HTML, how to show the ability of JS?

Let’s start with a simple taste of what JSX can do:

  • Dynamic display of data {}

  • Call method: custom + built-in

  • Supports expressions, supports ternary expressions

  • Template string

Next, let’s work on it:

import React from 'react'; import ReactDOM from 'react-dom'; Function sayHello () {return 'const obj' = {name: 'liu ', age: 100} const flag = true ==== const title = (<h2> hey hey </h2>) // JSX = (< div> {/* comment on JSX Is such a bear like * /} < p > name < / p > {/ * this mandarin duck (as) shows the * /} < p > {name} < / p > dynamic access to variable data * /} {/ * < p > {sayHello ()} < / p > {/ * a function called illegal? Does it make sense to execute native JS without */} {/*? Reasonable * /} < p > {the console. The log (' 1111 ')} < / p > < p > {Math. The random ()} < / p > < p > {JSON. Stringify (obj)} < / p > {/ * ternary operation let you are jealous? No */} <p>{flag? 'Login status' :' Perform login '}</p> {/* Under template characters, strings and variables are married, ok? Can * /} < p > {` hello, `} < / p > ${name} {/ * JSX yo also can be directly edible value * /} < div > {title} < / div > < / div >). ReactDOM render (App, document. GetElementById (" root "));Copy the code
  • JSX is itself an expression

  • JSX adds attributes:

    • String property, wrapped directly in double quotes
    • Dynamic properties, use {} instead of double quotesclass={xxx}
  • JSX adds child elements

    • JSX has only one parent element
  • The single label must be closed

// 01 JSX is an expression const names = <h3> </h3> // 02 Add attribute const age = 99 // 03 JSX add child element (JSX has only one parent element) // 04 Single tag must be closed // Function App() {return (// only one JSX block is returned // <p></p> // error <div> {/* JSX is an expression */} {names} {/* Add attributes */} <p Age = "age" > user age attribute < / p > {/ * * / string attribute} < p age = {age} > user age attribute < / p > {/ * dynamic properties * /} {/ * single label must be closed * /} {/ * < img > * /} {/ * error * /} {/ * single label <img /> </div>); } export default App;Copy the code

Finally, JSX is best wrapped with a parenthesis ();

event

Event handlers and event bindings

Const event1 = function(){alert(' hey hey React')} function App (){return (<div> <h1> </h1> {/* <button onClick={event1}> </button> </div>)} export default AppCopy the code

Event pass arguments

Because the event binding requires the receiving function itself, handled as an event, it cannot be called directly

Const event1 = function(name,age){alert(name) alert(age)} function App (){return (<div> <h1> event </h1> {/* Because the event binding needs to receive the function itself, handled as an event, <button onClick={()=>{event1(' west ',16)}}> </button> <br /> {/* <button onClick={event1.bind(null,' ying ying ',999)}> JS */} </div>) export default AppCopy the code

Therefore, you need to use the arrow function to return the event handler, not the function call, or use bind, etc., to pass in the function itself as the return value.

Again, JSX is JS extension, JS

The event object passes parameters

01 Function has no parameters:

The event object is passed in by default, so the parameter is received directly in the event handler.

02 Arrow function parameters:

Since the event object is passed in by default, when using arrow functions, you need to pass it in the arrow function and then in the function returned by the arrow function.

03 Bind, etc. :

Pass in the function itself as the return value, and the event object is added to the last argument by default.

Event objects do not need to be written, regardless of whether arguments are passed in. Event handlers receive them sequentially

Const event1 = function (ev) {console.log(ev); } function App() {return (<div> <h1> </h1> {/* 01 } <button onClick={event1}> </button> <br /> {/* 02 Arrow function parameter Since the event object is passed in by default, when using arrow function, */} <button onClick={(ev) => {event1(ev,' west ', </button> <br /> {/* 03 bind, bind, bind, bind, bind Bind (null)} </button> </div>) export default AppCopy the code

The list of rendering

JSX structures arrays by default, so you can display the values of arrays directly in JSX.

Const item1 = [1,3,5] function App() {return (<div> {/* JSX structures arrays */} <h1>{item1}</h1> </div>)} export default AppCopy the code

Similarly, if the array element value is also JSX, it can also be used directly.

Const item2 = [<p> Item1 </p>, <p> Item1 </p>, <p>item1</p>] function App() {return (<div> {/* JSX) {return (<div> {/* JSX) {/ /} <h1>{item1}</h1> {/* JSX) {item2} </div> </div> ) } export default AppCopy the code

In the project, most of the array elements obtained are object data, which need to be used after cyclic operation of the array to display its structure.

// const arr = [{id: 1, name: 'I'}, {id: 2, name: 'I'}, {id: 3, name: 'I'} Loops () {var I = [] loops() {var I = 0; i < arr.length; Push (<h1 key={arr[I].id}>{arr[I].name}</h1>)} return a2} function App() {return (< div>) } {loops()} </div>)} export default AppCopy the code

This method is not recommended because it is too complicated.

However, the basic idea remains the same. Since JSX automatically constructs array structures, we only need to traverse the data as JSX data. Therefore, we can choose a more elegant traversal method, map() function;

// const arr = [{id: 1, name: 'I'}, {id: 2, name: 'I'}, {id: 3, name: 'I'} 'nan shan difficult}] function App () {return (< div > {/ * * iterate through the map method group /} {arr. The map (item = > < h3 > {item. Id} - {item. The name} < / h3 >)} < / div >) } export default AppCopy the code

The style is set

Inline style

Styles need to be presented as objects:

// Declare the style object const styles = {color:'red', // The style attribute name needs to be handled, either // font size:'20px', // use the error fontSize:'30px', Function App (){return (<div> {/* Inline styles need to be displayed as objects */} <h3 Style ={{color:"red"}} > </h3> <p style={styles}> </p> </div>)} export default AppCopy the code

Outreach style

Create the corresponding CSS file and use the modular syntax rules to introduce the style file.

Create the CSS file \ SRC \ app.css

body{
  background-color: skyblue;
  color: blue;
}

.box{
  font-size: 30px;
}
Copy the code

\src\App.js

// app.css 'function App (){return (<div> <h3> <p className="box"> </p> </div>)} export  default AppCopy the code

Conditions apply colours to a drawing

Conditional rendering is a function call.

import React from 'react' import ReactDom from 'react-dom' var f = false const fun1 = ()=>{ if(f){ return <h1> hahaha </h1>)}else{return (<h2> hey hey </h2>)}} const title = ( Code cleaner < div > {fun1 ()} < / div >). ReactDom render (title, document getElementById (" root "))Copy the code

conclusion

JSX is a very important part of React. The most important thing in programming is UI rendering. JSX is the JavaScript version of HTML, or you can use JavaScript to write HTML.