Component creation
Class Components
Class components refer to components defined in ES6 called class components
When importing a class component, the component name must be capitalized.
Class components must inherit the parent class (relevant methods and attributes will be inherited)
render is a fixed function (must have), has a return value, and returns the structure of the class component (jsx)
🏸Define class components and expose them
import React from 'react' //App is a class name. It can be inherited at will (fixed, not discarded)class App extends { render(){ render(){ //If you want to enter the car, you must add () //2. There can only be one label on the outermost layer, and there cannot be brothers parallel. return ( <section> hello react <ul> <li>1111</li> <li>222</li> </ul> <div>New content111</div> <div>New content2222</div> </section> ) } } } export default App //Export: Convenient to be referenced by other components
🏸Import the required App class components in the entry file under src
React 17Previous version import React from 'react' import ReactDOM from 'react-dom' import App from "./01-base/01-class component" // It must be capitalized when introducing(<App></App>,("root")) ...................................... React 18Version import {createRoot} from 'react-dom/client' import App from "./01-base/01-class component" //Import App Componentsconst container = ('root') const root = createRoot(container); // Where to put the App(<App/>) //One or even labels are OK
Functional Components
function App(){ return ( <div> hello functional component <div>111</div> <div>2222</div> </div> ) } export default App
Nesting of components
import React, { Component } from 'react' class Child extends Component{ render(){ return <div>child</div> } } class Navbar extends Component{ render(){ return ( <div> navbr <Child></Child> </div> ) } } function Swiper(){ return <div>swiper</div> } const Tabbar = ()=> <div>tabbar</div> //The above three seed components can be nestedexport default class App extends Component { render() { return ( <div> <Navbar></Navbar> <Swiper></Swiper> <Tabbar></Tabbar> </div> ) } } ........................................ import App from "./01-base/03-Nesting of Components" import {createRoot} from 'react-dom/client' const container = ('root') const root = createRoot(container); (<App/>)
Component style
In-line style is recommended, because React feels that each component is an independent whole
In-line style
If you want to add inline styles to the virtual dom, you need to use the expression to pass the style object to achieve it.
render() { var myname = 'xiaoming' var isChecked = false var obj = { backgroundColor:"yellow", fontSize:""//Camel nomenclature } return ( <div> {myname}-{10+20}-age {10>20?"a":"b"} <div style={obj}>111</div> <div style={style={{textDecoration:isChecked?"line-through":''}}> //There are two brackets here. The first one means that we need to insert JS into JSX again, and the second one is the brackets of the object. <div style={{background:"red"}}>222</div> </div> ) }
🔎1. {} is a js expression, and statements are not supported
🔎2. The style in the line needs to be written into a style object such as the obj above. The location of this style object can be placed in many places, such as in the render function, on the component prototype, and in the external link js file.
class style
- Write styles in css file
- Import css file
- Add class class name to the element (class needs to be written as className. When writing class js code, it will be subject to the existence of js rules, and class is a keyword)
<div className="active">333</div> <div >444</div>
⭐️⭐️ ⭐️ class ==> className,for ===> htmlFor(label) ⭐️⭐️ ⭐️
<label htmlFor='username'>username:</label> <input type="text" ></input>
Event handling
Event binding
📢Use arrow function in render—use this directly
a = 100 render(){ return( <button onClick={ ()=>{ ("click1","If the processing logic is too much, it is not recommended",); } }>add1</button> ) }
The scope of the arrow function is App, so this is directly App
📢Call function in render, function normal function - use bind to change this pointing
a = 100 render(){ return( {/* call, apply to change this pointing and automatically execute the function; bind to change this pointing and not automatically execute */} <button onClick={ this.(this)}>add2-Not recommended</button> ) } handleClick2(){ ("click2",) }
Just start with this in render, change this to App by using bind
📢Call function in renderer, function arrow function – use this directly
a = 100 render(){ return( <button onClick={ this.handleClick3 }>add3-Comparatively recommended</button> ) } handleClick3 = ()=>{ ("click3",) }
📢Calling functions using arrow functions in renderer – use this directly
a = 100 render(){ return( {/* Very recommended */} <button onClick={ ()=>{ this.handleClick4() } }>add4</button> {/* Call handleClick4 after executing anonymous function */} ) } handleClick4 = ()=>{ ("click4",) }
This in onClick is an App, so when handleClick is called, whether it is an arrow function or a normal function this is the same as the caller.
Parameter pass of event
🎐1. Bring a layer of arrow function outside the place where the method is called in render
🎐2. Pass in render through (this, parameter)
🎐3. Pass through event
Application of ref
📌Set ref="mytext" for the tag
<input ref="mytext"></input> <button onClick={ ()=>{ ("click1",); } }>add1</button>
through ref, you can get the real dom of the application
📌 Set ref="username for component
Through this acquisition, ref can obtain component object
📌New writing method (under strict mode)
myref = () <input ref={}></input> <button onClick={ ()=>{ ("click",); } }>add1</button>
access
State (state)
Status is the data that the component describes a certain display situation, which is set and changed by the component itself, that is, the component maintains itself. The purpose of using the status is to create different displays in different states (manage them by themselves).
Define state
state={ mytext:"collect", myShow:true } render(){ return( <div> <h1>welcome</h1> <button onClick={()=>{ // = "Cancel Favorites" Don't directly modify state }}>{}</button> </div> ) }
It is a pure js object. In vue, the data attribute uses the processed data. When changing the data, it returns the getter and setter of the data. However, there is no such processing in React. If it is changed directly, react cannot know, so it is necessary to use setState to modify it indirectly.
setState
myShow is stored in the state object of the instance. In the component's render function, "Cancel" or "Favorite" will be displayed according to the different myShow in the component's state.
Multiple statuses can be updated at once
import React, { Component } from 'react' export default class App extends Component { // state={ // mytext:"Favorite", // myShow:true // } constructor(){ super()// Must write ={ mytext:"collect", myShow:true, myName:"xiaoming" } } // ! ! ! ! Both of the above state writing methods are OK!!! render() { return ( <div> <h1>welcome--My name is{}</h1> <button onClick={()=>{ // = "Cancel Favorites" Don't directly modify state ({ //mytext:"Cancel Favorites" myName:'zhangsan', myShow:! })//Indirectly modify state if(){ ("Collect Logic"); }else{ ("Cancel logic"); } }}>{?'collect':'Cancel Favorites'}</button> </div> ) } }
setState synchronous asynchronous
- setState is in the synchronous logic, updating the status asynchronously, updating the real dom
- setState is in asynchronous logic, synchronously updates the status and synchronously updates the real dom
- setState accepts the second parameter, and the second parameter callback function, the status and dom will be triggered after the update of the second parameter will be triggered.
Supplement - React Interview Questions
The difference between react event binding and normal event binding
React does not really bind events to each specific element, but adopts the event proxy mode and binds them to the root node.
Event object
Like ordinary browsers, event handlers will be automatically passed into an event object, which is basically the same as the methods and properties contained in ordinary browser event objects. The difference is that the event object in React is not provided by the browser, but is built internally. He also has this common method
This is the end of this article about the detailed explanation of the creation of React components synchronously and asynchronously with state. For more related content on creating React components, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!