1. Install React
Get the default index.html and package.json ready in the root integration terminal: NPM I react React -dom
- The React package is the core, providing the ability to create elements, components, and so on
- The React-dom package provides DOM-related functionality (rendering created elements to pages)
2. React
2.1 Initialize the project using the React scaffolding
-
NPX create-react-app Project name
When your project (named my-app) is successfully installed, you see Happy Hacking!
-
To start the project, run the NPM start command in the project root directory (CD my-app)
If YARN is installed, use YARN start
Yarn Command Introduction
- Yarn is a package manager published by Facebook. It can be regarded as an alternative to NPM and has the same functions as NPM
- Yarn is fast, reliable, and secure
- Initialize a new project: YARN Init
- Installation package: YARN add Package name
- Installation project dependency: YARN
-
Automatically redirects to http://localhost:3000/
It can also be accessed by opening the link at the integration terminal (right-click the element)
2.2 Use React in Scaffolding
(in SRC index.js)
- Import react and react-dom packages
import React from 'react'
import ReactDOM from 'react-dom'
Copy the code
- Create react elements using JSX syntax
let h1 = <h1>I created the element through JSX</h1>
Copy the code
-
Render the React element to the page
The reactdom.render () method renders the created React element H1 (or component parameters) to the page
Parameter 1: React element to render Parameter 2: DOM object, which specifies where to render elements on the page (mount point)Copy the code
ReactDOM.render(h1,document.getElementById('root')) // Get the DOM object from the page with id root as the mount point
Copy the code
Pay attention to the point
- React element attribute names use camel name
- Special attribute names: class -> className, for -> htmlFor, tabIndex -> tabIndex
- The React element can be used if there is no child node
/>
To the end- Recommendation: Wrap JSX in parentheses to avoid automatic insertion of semicolons in JS
import React from 'react'
import ReactDOM from 'react-dom'
//span has no child nodes
const title = (
<h1 className="title">
Hello JSX
<span />
</h1>
)
// Render the react element
ReactDOM.render(title, document.getElementById('root'))
Copy the code
Check elements:
<body>
<div id="root">
<h1 class="title">
"Hello JSX"
<span></span>
</h1>
</div>
</body>
Copy the code
3. JSX grammar :(★★★)
3.1 Embedding JS expressions
That is, data stored in JS is presented in JSX
Syntax: {JavaScritp expression}
let content = 'Inserted contents' // Data stored in js
let h1 = ( <h1>I created the element with JSX + {content}</h1> )
Copy the code
Pay attention to the point
- Any valid JS expression (such as a variety of data types) can be embedded
- JSX is itself a JS expression
const h1 = <h1>I am the JSX</h1> //h1 is JSX. JSX is itself a JS expression and can also be embedded in JSX
const dv = (
<div>Embedded expression: {h1}</div>
)
Copy the code
- Note: objects in JS are not embeddable and usually only appear in the style property
- Note: statements (such as if/for) cannot appear in {}
import React from 'react'
import ReactDOM from 'react-dom'
// Function call expression
const sayHi = () = > 'Hi~' // Returns the string Hi~ after the function call
const dv = <div>I'm a div</div> / / dv is JSX
const title = (
<h1>
Hello JSX
<p>{1}</p>
<p>{'a'}</p>
<p>{+ 7} 1</p>
<p>{3 > 5? 'greater than' : 'less than or equal to '}</p>
<p>{sayHi()}</p>{dv} {/*JSX is itself a JS expression and can also be embedded in JSX */} {/* Error: comments are in JS. Comments embedded in JSX also need to be enclosed in curly braces */} {/*<p>{ {a: '6'} }</p>*/} {/* {if (true) {}}} {/* {for (var I = 0; i < 10; I++) {}} braces cannot contain statements */}</h1>
)
// Render the react element
ReactDOM.render(title, document.getElementById('root'))
Copy the code
3.2 Conditional Rendering
Scenario: Loading effect
Return a different JSX structure, depending on the judgment logic, and then render it to the page:
let isLoading = true
let loading = () = >{
if(isLoading){
return <div>Loading...</div>
}
return <div>loaded</div>
}
Copy the code
Use if/else or ternary operators or logical and operators
import React from 'react'
import ReactDOM from 'react-dom'
/* Conditional rendering: */
const isLoading = false
// if-else
// const loadData = () => {
// if (isLoading) {
// return
loading...
/ /}
// }
// if ();
// const loadData = () => {
// return isLoading ? (
loading...
) : (
data loading completed, here is the loaded data
)
// }
// Logic and operators:
const loadData = () = > {
return isLoading && (<div>loading...</div>)}const title = (
<h1>Conditional rendering: {loadData()} {/* Embed function calls in JSX*/}</h1>
)
// Render the react element
ReactDOM.render(title, document.getElementById('root'))
Copy the code
3.3 List Rendering
-
Render a set of data using the map () method of an array
The map() method returns a new array with the values of the original array elements processed by the sequential calls to the function.
arr.map()
- Note: The key attribute must be added to render the list. The value of the key attribute must be unique
- Rule: Map () adds a key attribute to whoever the map() traverses
- Note: Avoid using (variable) index numbers as keys
let arr = [{
id:1.name:Romance of The Three Kingdoms}, {id:2.name:'Water Margin'}, {id:3.name:Journey to the West}, {id:4.name:A Dream of Red Mansions
}]
const list = (
<ul>
{arr.map(item => <li key={item.id}> {item.name} </li>)}
</ul>
)
ReactDOM.render(list,document.getElementById('root'))
Copy the code
3.4 Style Processing
Inline style -style
In the style of objects embedded, cumbersome, inconvenient to read
<li key={item.id} style={{'color': 'red'."backgroundColor": 'pink'}}>{item.name}</li>
Copy the code
ClassName -className (recommended)
Create CSS file write style code (SRC CSS folder)
.title {
text-align: center
}
Copy the code
In js, set the class name
import React from 'react'
import ReactDOM from 'react-dom'
/ / into the CSS
import './css/index.css'
const list = (
<h1 className="title" style={{ color: 'red', backgroundColor: 'skyblue' }}>JSX style handling</h1>
)
// Render the react element
ReactDOM.render(list, document.getElementById('root'))
Copy the code
summary
- JSX is at the heart of React
- JSX stands for writing HTML structures in JS code and is the embodiment of React declarative style (just describing what the page looks like)
- Arbitrary UI structures can be described using JSX with embedded JS expressions, conditional rendering, and list rendering
- It is recommended to style JSX using a className