1, React project creation
1. Introduce third-party plug-ins to create React project
- Install third-party plug-ins
npm i react react-dom
- Introduce react DOM into the page
<script src="./node_modules/react/umd/react.development.js"> <script src="./node_modules/react-dom/umd/react-dom.development.js">
- Create React element
// Create element node // 1. Element name // 2. The element attribute passes an object // 3. Element content let title = React.createElement('li',null,'hellow react');
- Render to page
// Render to page ReactDom.render(title,root);
2. Create React project for scaffold
- 1. Create project
npm5.2+ (npm Version 5.2 above) npx create-react-app my-project(Project name) npm5.2- (npm Version 5.2 following) npm i create-react-app -g create-react-app my-project(Project name)
- 2. Start the project
npm start / yarn start
2, React directory structure
- public folder
public -> Storing static resources
- src folder
src -> Store source code src/index.js Entry file
- gitignore
fill in git Files ignored when submitting code/folder
- package.json
Dependent download information
- README.md
Development documentation
Open hidden webpack configuration
npm run eject / yarn run eject
- Hidden config folder
webpack to configure
- scripts
Environment configuration build.js production environment start.js development environment test.js testing environment
3, React basic syntax
JSX Not standard ECMAScript grammar,It is ECMAScript Grammatical expansion of Need to use babel After compilation,Can be used in the browser environment create-react-app This configuration is already in the scaffold by default,No manual configuration required compile JSX Syntax package: @bable/prest-react React The attribute name of the element uses the hump naming method Special attribute name: class->className for->htmlFor tabindex->tabIndex If there are no child nodes React Element can be used/>To end recommend: Wrap in parentheses JSX,So as to avoid JS Error in automatic insertion of semicolon in
JSX
- Virtual DOM
// First kind import React from 'react' import ReactDOM from 'react-dom' const mydiv = React.createElement('div',null,'I am a div'); ReactDOM.render( mydiv, document.getElementById('root') ) // Second import React from 'react' import ReactDOM from 'react-dom' ReactDOM.render( <div>I am a div</div>, document.getElementById('root') )
- Template syntax
import React from 'react' import ReactDOM from 'react-dom' let msg = 'hello react' ReactDOM.render( <div> {msg} </div> document.getElementById('root') )
- conditional rendering
//First kind import React from 'react' import ReactDOM from 'react-dom' let isloading = false function isShowUI() { if(isloading) { return <div>loading...</div> } else { return <div>done</div> } } ReactDOM.render( <div> {isShowUI()} </div> document.getElementById('root') )
//Second (ternary operator) import React from 'react' import ReactDOM from 'react-dom' let isloading = false ReactDOM.render( <div> {isloading?'loading...':'done'} </div> document.getElementById('root') )
//The third (concise way to show / hide) import React from 'react' import ReactDOM from 'react-dom' let isloading = false ReactDOM.render( <div> {isloading&&'loading...'} </div> document.getElementById('root') )
- List rendering
import React from 'react' import ReactDOM from 'react-dom' let list = [ { id:0, name:'fly' }, { id:1, name:'sky' } ] ReactDOM.render( <div> {list.map(item=>{ return <p key={item.id}>{item.id}----{item.name}</p> })} </div> document.getElementById('root') )
- Style binding
import React from 'react' import ReactDOM from 'react-dom' //import './index.css' import './index.scss' //Using scss import classNames form 'classnames' let isloading = false let objStyle = { color:'red' } ReactDOM.render( <div> <h1 className="title">Style binding-className</h1> <h2 style={{ color:'red' }}>Style binding-style</h2> <h2 style={objStyle}>Style binding-style(External object writing)</h2> <h2 className={classNames({ title:true, active:true })}>Style binding-Multiple class names classnames</h2> </div> document.getElementById('root') )
.title{ color:red; } .active{ text-decoration:line-through; }
************************************************************************************************ Used when one label has more than one class name classnames need yarn add classnames install classnames plug-in unit then import classNames form 'classnames' introduce ************************************************************************************************
4, React component
1. Function components
1.use js Create component using function 2.Function names must start with uppercase letters 3.A function component must have a return value,Represents the structure of the component 4.If the return value is null,Indicates that nothing is rendered
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; // Define components in a functional way (the first way to write functional components) // 1. Function name is capitalized // 2. The function requires return /* function App(){ // return null; // return <div> <span>app</span> </div>; // Add () to make it easier to view. It can be omitted return (<div> <span>app</span> </div>); } */ // The second way to write function components /* const App = () => { return ( <div> <span> app </span> </div> ) } */ ReactDOM.render( <App />, document.getElementById('root') );
2. Class components
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; // Define components in class mode class App extends React.Component { render() { return ( <div> <span> app </span> <MyComponent /> </div> ) } } ReactDOM.render( <App />, document.getElementById('root') );
3. Custom components
stay src Next custom js file(Name is the custom component name),You can't be here src lower,Create another one components Folders are dedicated to storing components
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-nptohzhc-1634049746098) (C: \ users \ Qifen \ appdata \ roaming \ typora \ user images \ image-20210731163417042. PNG)]
- Custom function component
MyComponent.js import React from 'react' export default function MyComponent(){ return ( <div> With arrow?Functionally defined components,Generally, it is only used for rendering---/---Components have a lifecycle,Components defined functionally have no lifecycle,You can improve rendering speed </div> ); }
first import Introduce custom components 1.Directly in ReactDOM.render Using custom components in 2.Defined in the current file(function/class)Component import custom component
index.js import React from 'react'; import ReactDOM from 'react-dom'; import MyComponent from './MyComponent.js' //Custom components import './index.css'; class App extends React.Component { render() { return ( <div> <span> app </span> <MyComponent /> </div> ) } } ReactDOM.render( <App />, // <MyComponent />, document.getElementById('root') );
- Custom class component
import React,{ Component } from 'react' export default class ClassComponent extends Component{ render() { return ( <div> <RCF /> <RCC /> </div> ); } }
- Assembly sleeve assembly
Create a new compoents Folder storage component,stay src Import in the customized component file under
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-9nazi5qk-1634049746100) (C: \ users \ Qifen \ appdata \ roaming \ typora user images \ image-20210731170858344. PNG)]
import React,{ Component } from 'react' import RCF from './compoents/RCF.js' //Introduce custom components import RCC from './compoents/RCC.js' //Introduce custom components export default class ClassComponent extends Component{ render() { return ( <div> <RCF /> <RCC /> </div> ); } }
index.js By introducing this component into the file, the dolls can be realized
4. Controlled components
HTML The form elements in are editable,That is, it has its own variable state and React Variable states are usually saved in state in,And only through setState()Method to modify React speak state And form elements value Bind together,yes state To control the value of the form element Controlled components:Value affected react Controlled form elements Controlled components are stateful components
import React,{ Component } from 'react' export default class ShouKong extends Component{ // constructor() { // super() // this.state = { // Value: 'value in constructor' // } // } state = { value:'hello react' } render() { const { value } = this.state; return ( <div> <div>{value}</div> <input value={value} onChange={this.handleChangeValue} /> </div> ); } handleChangeValue = (e) => { this.setState({ value:e.target.value }) // The second writing method does not explain its purpose // this.setState(()=>{ // return { // value:e.target.value // } // }) } }
5. Uncontrolled components (including ref use)
explain:With the help of ref,Use element DOM Get form element value by ref Role of:obtain DOM Or component Use steps: call React.createRef()Method creation ref object The created ref Object to the text box adopt ref Object gets the value of the text box
- The first way is to connect this.refs directly through ref
import React,{ Component } from 'react' export default class FeiShouKong extends Component{ render() { return ( <div> <input ref="inputRef"/> <button onClick={this.handleClick}>Point me</button> </div> ); } handleClick = () => { console.log(this.refs.inputRef); // Get ref object console.log(this.refs.inputRef.value); // Get the value of the input field of the ref object } }
- The second way is to combine createRef with constructor
import React,{ Component, createRef } from 'react' export default class FeiShouKong extends Component{ constructor() { super() this.inputRef = createRef() } render() { return ( <div> <input ref={this.inputRef}/> <button onClick={this.handleClick}>Point me</button> </div> ); } handleClick = () => { console.log(this.inputRef.current); // Get the current ref object console.log(this.inputRef.current.value); // Get the value of the input field of the ref object } }
The difference between the two methods 1.Data binding the first data binding is ref="inputRef" The second is ref={this.inputRef} 2.The first type of constructor does not need to go to the constructor, and the second type needs to be in the react in import introduce createRef Method in constructor this.inputRef = createRef() Initialize a variable by createRef()method 3.obtain ref Object first this.refs.inputRef Second this.inputRef.current 4.The first is 16.3 The second version is the new version
5, React event handling
React Event binding syntax close js Native grammar grammar: on+Event name=Event handler, ps:onclick = function(){} be careful:React Hump naming method is adopted for the event
onClick The writing method and original js What follows is{this.handleClick.bind(this)} this.handleClick Yes react The reason why the function in the object.bind(this)Because you need to get it state(stay react object)Value in Hierarchy and of functions render Function consistency,be similar to wxapp state be similar to vue(wxapp)of data Values and changes are similar to wxapp
Four event bindings can be obtained state Method of Li value
- The first method: change this to point to the react object through bind
- The second is to point to the context object (react object) by using the arrow function, where the function call needs to add ()
- The third method: use bind in the constructor to change the direction of this (the third method needs to be used in combination with the constructor)
- The fourth method is to define functions in the form of arrow functions
- The third / fourth is recommended
import React,{ Component } from 'react' export default class ClassComponent extends Component{ constructor() { // Use in conjunction with the third method super() this.state = { msg:'Constructor msg' } this.handleClick = this.handleClick.bind(this); } state = { msg:'hello react' } render() { return ( <div> with class Class(Class component,There is a life cycle)<br/> {/*this.handleClick The function in the react object needs. bind(this) because it needs to get the value in state (in the react object)*/} {/* The first method: change this to point to the react object through bind */} <button onClick={this.handleClick.bind(this)}>Point me</button> {/* The second is to point to the context object (react object) by using the arrow function, where the function call needs to add ()*/} <button onClick={() => this.handleClick()}>Point me</button> {/* Third: use bind in the constructor to change the direction of this */} <button onClick={this.handleClick}>Point me</button> {/* The fourth method is to define functions in the form of arrow functions */} <button onClick={this.handleClickArr}>Point me</button> </div> ); } handleClick(){ // console.log("it's me"); console.log(this.state.msg); } handleClickArr = () => { console.log('Arrow function'+this.state.msg); } }
- expand
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-oogbqh1u-1634049746101) (C: \ users \ Qifen \ appdata \ roaming \ typora user images \ image-20210801170619256. PNG)]
6, this.setState implements bidirectional binding
- Stateful component / stateless component
Functional components are also called stateless components,Class components are also called stateful components state(state)Namely data A function component does not have its own state,Only responsible for data display Class components have their own state,Responsible for updating UI,Make the page move human speech:yes state(data data)It's a state,Otherwise, it is stateless,The function component is stateless,Class components are stateful components
react in jsx take state Values in ps:<div>{this.state.msg}</div> this.setState Is an asynchronous request that implements two-way binding,So we need to use the following two ways to achieve it // The first asynchronous method uses the callback function in the setState method to realize asynchronous call // The second is asynchronous. async await is recommended
import React,{ Component } from 'react' export default class StateBind extends Component{ // I don't know the difference between the state in the constructor and the normal state // constructor() { // super() // this.state = { // msg: 'msg in constructor' // } // } state = { msg:'hello react' } render() { return ( <div> <div>{this.state.msg}</div> <input value={this.state.msg} onChange={this.handleChangeTwo} /> </div> ); } handleChange = (e) => { // It is the same as getting the value of input in wxapp // console.log(e.target.value); // Because this is an asynchronous function, we can't determine who will execute the print first this.setState({ msg:e.target.value }); console.log(this.state.msg); } // The arrow function is written here to point to this handleChangeOne = (e) => { // The first asynchronous method uses the callback function in the setState method to realize asynchronous call this.setState({ msg:e.target.value },()=>{ console.log(this.state.msg) }); } handleChangeTwo = async (e) => { // The second is asynchronous. async await is recommended await this.setState({ msg:e.target.value }); console.log(this.state.msg) } }
7, React component value transfer
React Component advanced: 1.Can use props receive data 2.It can realize the communication between parent and child components 3.It can realize the communication between brother components 4.Ability to add to components props check
Component communication:Because components are independent and closed units,By default, only the component's own data can be used,Multi component shared data,It is necessary to break the independent closure of components
1. props of components
The components are enclosed,External data should be received through props realization props Role of:Receive data passed to components Transfer data:Add properties to component labels example:<Hello name="jack" age={19} /> The internal component cannot control or modify the external incoming props
characteristic: Any type of data can be passed to the component props Is a read-only property,The value cannot be modified be careful:When using class components,If you write a constructor,Should props Pass to super(),Otherwise, it cannot be obtained in the constructor props,Other places are available
import React,{ Component } from 'react' import Rcc from './components/Rcc.js' import Rfc from './components/Rfc.js' export default class APP extends Component{ render() { return ( <div> <Rfc title={'title'} /> <Rcc title={'title'} /> </div> ); } }
- Function component (props)
Function components pass parameters props receive data <Rfc title={'title'} />
Rfc Component function component import React from 'react' export default function Rfc(props){ console.log(props); return ( <div> Stateless component --- {props.title} </div> ); } // Stateless component - title
- Class component (this.props)
<Rcc title={'title'} /> Class component passed this.props receive data You can also state To save props Value passed this.state.xxx But it needs to be done again constructor afferent props Parameter acquisition props Re deposit this.state in,Otherwise, directly in state Error message when used in props non-existent???*****************************Not yet,Remember to check and study when you have time**************************************
Rcc Component class component import React,{ Component } from 'react' export default class Rcc extends Component{ // Class components can be obtained through the constructor to operate props constructor(props) { super(props); this.state = { title: props.title } }; // An error will be reported, indicating that the title cannot be found // state = { // title: this.props.title // } render() { return ( <div> Stateful component --- {this.props.title} {this.state.title} </div> ); } } // Stateful component - title
- Function component (props.children)
Function components pass parameters props.children Get all child elements under the component <Rfc>title<h1>Ha ha ha</h1></Rfc>
Rfc Component function component import React from 'react' export default function Rfc(props){ console.log(props); return ( <div> {/* props.children Get all child elements under the component */} Stateless component --- {props.children} </div> ); } // Stateless component - title // Ha ha ha
- Class component (this.props.children)
Class component passed this.props.children Get all child elements under the component <Rcc>title<h2>Hey, hey, hey</h2></Rcc>
Rcc Component class component import React,{ Component } from 'react' export default class Rcc extends Component{ // Class components can be obtained through the constructor to operate props constructor(props) { super(props); this.state = { title: props.title } }; render() { return ( <div> Stateful component --- {this.props.children} </div> ); } } // Stateful component - title // Hey, hey, hey
2. Son to father
react The principle and application of "son to father" vue be similar,Closer to primary Add attribute pass in function when parent component renders child component <SonToFatherRcc getData={this.getData} /> getData(data){ console.log(data) } Sub component acquisition props And make a call to pass in parameters,The parent component gets the parameter,Both son and father <button onClick={this.handelClick}>Child parent class component</button> handelClick = () => { this.props.getData('Data passed from child to parent of class component') }
import React,{ Component } from 'react' import SonToFatherRcc from './components/SonToFatherRcc.js' import SonToFatherRfc from './components/SonToFatherRfc.js' export default class APP extends Component{ render() { return ( <div> <SonToFatherRcc getData={this.getData} /> <SonToFatherRfc getData={this.getData} /> </div> ); } getData(data){ console.log(data) } }
- Class component
import React,{ Component } from 'react' export default class SonToFatherRcc extends Component{ render() { return ( <div> Stateful component <button onClick={this.handelClick}>Child parent class component</button> </div> ); } // Use the arrow function, otherwise you can't use this directly, because this in the function points to undefined handelClick = () => { this.props.getData('Data passed from child to parent of class component') } } // Console print: data passed from child to parent of class component
- Function component
import React from 'react' export default function SonToFatherRfc(props){ console.log(props); const handelClick = () => { props.getData('Data passed from child to parent of function component') } return ( <div> Stateless component --- <button onClick={handelClick}>Function component child parent</button> </div> ); }
3. Brother value transfer
1.Share status(data)Promote to the nearest public parent component,This state is managed by the public parent component 2.This is called state ascension 3.Common parent component responsibilities: Provide shared state provides methods for operating shared state 4.The subcomponents to communicate only need to pass props Method of receiving state or operating state
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-h3ouyy39-163404946102) (C: \ users \ Qifen \ appdata \ roaming \ typora user images \ image-2021092215032162. PNG)]
In essence, it is the combination of son to father and father to son
import React,{ Component } from 'react' import BrotherRcc1 from './components/BrotherRcc1.js' import BrotherRcc2 from './components/BrotherRcc2.js' import BrotherRfc1 from './components/BrotherRfc1.js' import BrotherRfc2 from './components/BrotherRfc2.js' export default class APP extends Component{ state = { count:0 } render() { return ( <div> <BrotherRcc1 count={this.state.count}/> <BrotherRcc2 addCount={this.addCount}/> <BrotherRfc1 count={this.state.count}/> <BrotherRfc2 addCount={this.addCount}/> </div> ); } addCount = (data) => { // this.setState({ // count: this.state.count + data // }) /* In this way, the latest state state is obtained first, and then relevant changes are made, It can prevent different state changes due to the influence of time delay such as timer */ this.setState((nextState)=>{ return{ count:nextState.count + data } }) } }
- Class component
BrotherRcc1 Component presentation rendering,The link between father and son import React,{ Component } from 'react' export default class BrotherRcc1 extends Component{ // Class components can get props through constructors constructor(props) { super(props); this.state = { title: props.title } }; render() { return ( <div> Stateful count:{this.props.count} </div> ); } }
BrotherRcc2 Component value passing operation is the link from child to parent import React,{ Component } from 'react' export default class BrotherRcc2 extends Component{ // Class components can get props through constructors constructor(props) { super(props); this.state = { title: props.title } }; render() { return ( <div> <button onClick={this.add}>Stateful addition</button> </div> ); } add = () => { this.props.addCount(1); } }
- Function component
BrotherRfc1 Component presentation rendering,The link between father and son import React from 'react' export default function BrotherRfc1(props){ return ( <div> Stateless component Count:{props.count} </div> ); }
BrotherRfc2 Component value passing operation is the link from child to parent import React from 'react' export default function BrotherRfc2(props){ const add = () => { props.addCount(1); } return ( <div> <button onClick={add}>Stateless component addition</button> </div> ); }
The parent component has a shared state One of the sibling components passes from parent to child to obtain the sharing status The child of another sibling component passes the parent to change the sharing state
4.Context value transfer
If there are many levels(for example:Grandpa passed it on to his grandson),We will use Context To deliver effect:Transfer data across components Context Two components are provided: Provider and Consumer Provider assembly: Used to provide data Consumer assembly: Used to receive(consumption)data
const { Provider, Consumer } = React.createContext() use Provider Component as parent node <Provider> <div> <Child1 /> </div> </Provider> set up value attribute,Represents the data to be transferred <Provider value="pink"> Which layer wants to receive data,Just use Consumer Package,The parameters in the callback function are the passed values <Consumer> {data = > <span>data The parameter represents the received data -- {data}</span>} </Consumer>
- Class component
import React,{ Component } from 'react' // Provider production Consumer consumption const { Provider, Consumer } = React.createContext(); // Grandpa component class ContextRcc extends Component{ state = { obj:{ name:'Xuxu baby', age:'25' } } render() { return ( <Provider value={this.state.obj}> <div> <h2>Master stateful component</h2> <Parent /> </div> </Provider> ); } } class Parent extends Component{ render() { return ( <div> <h2>Parent stateful component</h2> <Grandson /> </div> ); } } class Grandson extends Component{ render() { return ( <div> <h2>Grandson stateful component</h2> <Consumer> { data => <span>data Is from Provider I got it from value value -- {data.name+data.age}</span> } </Consumer> </div> ); } } export default ContextRcc
use<Provider value=xxxx></Provider>Package assembly For Sun Tzu assembly<Consumer>{data => <span>{data}</span>}</Consumer>receive Provider of value Value,There is no need to wrap the components
- Function component (usecontext not used)
import React, {createContext} from 'react' const FirstContext = React.createContext(); function ContextRfc(){ return ( <FirstContext.Provider value={18}> <div> <h2>Master stateless component</h2> <Parent /> </div> </FirstContext.Provider> ); } function Parent(){ return ( <div> <h2>Parent stateless component</h2> <Grandson /> </div> ); } function Grandson(){ return ( <div> <h2>Grandson stateless component</h2> <FirstContext.Consumer> { data => <span>data Is from Provider I got it from value value -- {data}</span> } </FirstContext.Consumer> </div> ); } export default ContextRfc
1.Compared to class components const { Provider, Consumer } = React.createContext();introduce Provider Components and Consumer assembly 2.Function component usage import React, {createContext} from 'react' introduce 3.And before use const FirstContext = React.createContext(); Define a context object 4.In traditional class components Provider and Consumer Add this variable object <FirstContext.Provider /> <FirstContext.Consumer /> 5.Other components are used in the same way as class components
- Function component (usecontext not used)
import React, {createContext,useContext} from 'react' const FirstContext = React.createContext(); function ContextRfc(){ return ( <FirstContext.Provider value={18}> <div> <h2>Master stateless component</h2> <Parent /> </div> </FirstContext.Provider> ); } function Parent(){ return ( <div> <h2>Parent stateless component</h2> <Grandson /> </div> ); } function Grandson(){ const data = useContext(FirstContext) return ( <div> <h2>Grandson stateless component</h2> <span>data Is from Provider I got it from value value -- {data}</span> </div> ); } export default ContextRfc
And not used useContext Compared with function components 1.When importing, more will be imported useContext import React, {createContext,useContext} from 'react' 2.stay Provider There is no difference in the use of components 3.stay Consumer Use of components,If used const data = useContext(xxxContext)Yes Provider of value You do not need to use Consumer Yes
5. Extract the component to realize Context value transfer
When not implemented within a single file Context When transmitting value,That is, master,Parents,The three components of the grandchildren are separated into separate files
- Class component
App.js import React,{ Component } from 'react' import GrandfatherRcc from './divisionContextRcc/GrandfatherRcc.js' export default class APP extends Component{ render() { return ( <div> <GrandfatherRcc /> </div> ); } }
GrandfatherRcc.js import React,{ Component } from 'react' import Parent from './Parent.js' import {Provider} from '../utils/contextUtil.js' // Introduce the Provider in the encapsulated tool component to ensure that the Context is consistent // In this way, you can't get the data passed by the master using the Context, because the Provider and Consumer are not the same React.createContext() // const {Provider} = React.createContext(); export default class GrandfatherRcc extends Component{ render() { return ( <Provider value={18}> <div> <h2>Master stateful component</h2> <Parent /> </div> </Provider> ); } }
Parent.js import React,{ Component } from 'react' import Grandson from './Grandson.js' export default class Parent extends Component{ render() { return ( <div> <h2>Parent stateful component</h2> <Grandson /> </div> ); } }
import React,{ Component } from 'react' import {Consumer} from '../utils/contextUtil.js' // Introduce the Provider in the encapsulated tool component to ensure that the Context is consistent // In this way, you can't get the data passed by the master using the Context, because the Provider and Consumer are not the same React.createContext() // const {Consumer} = React.createContext(); export default class Grandson extends Component{ render() { return ( <div> <h2>Grandson stateful component</h2> <Consumer> { data => <span>This is the data handed down by the master -- {data}</span> } </Consumer> </div> ); } }
Context tool import React from 'react' const { Provider, Consumer } = React.createContext() // If it is exposed through export default, it is in the form of an object export { Provider, Consumer }
If it is directly introduced in the parent component and the grandparent component respectively Provider,Consumer const { Provider, Consumer } = React.createContext() In this case, it is not introduced in a file,actually React.createContext()Objects are not the same,So the grandchildren certainly can't get the master's data So you need to encapsulate one first Context Tools for js file In this file const { Provider, Consumer } = React.createContext() then export Exposed Then in the parent component and the grandchild component respectively import introduce,This will ensure that it is the same Context,Grandchildren can get the master's data
- Function component (usecontext not used)
App.js import React,{ Component } from 'react' import GrandfatherRfc from './divisionContextRcc/GrandfatherRfc.js' export default class APP extends Component{ render() { return ( <div> <GrandfatherRcc /> </div> ); } }
Context tool import React, {createContext} from 'react' const FirstContext = React.createContext(); // If it is exposed through export default, it is in the form of an object export { FirstContext }
GrandfatherRfc.js import React from 'react' import Parent from './Parent.js' import {FirstContext} from '../utils/contextRfcUtil.js' export default function GrandfatherRfc(){ return ( <FirstContext.Provider value={25}> <div> <h2>Master stateless component</h2> <Parent /> </div> </FirstContext.Provider> ); }
Parent.js import React from 'react' import Grandson from './Grandson.js' export default function Parent(){ return ( <div> <h2>Parent stateless component</h2> <Grandson /> </div> ); }
Grandson.js import React, {createContext,useContext} from 'react' import {FirstContext} from '../utils/contextRfcUtil.js' export default function Grandson(){ return ( <div> <h2>Grandson stateless component</h2> <FirstContext.Consumer> { data => <span>data Is from Provider I got it from value value -- {data}</span> } </FirstContext.Consumer> </div> ); }
- Function component (using useContext)
Grandson.js Only this has changed relative to unused useContext import React, {createContext,useContext} from 'react' import {FirstContext} from '../utils/contextRfcUtil.js' export default function Grandson(){ const data = useContext(FirstContext) return ( <div> <h2>Grandson stateless component</h2> <span>data Is from Provider I got it from value value -- {data}</span> </div> ); }
Function component extraction implementation Context The tool component in the middle of value transfer only needs to be used createContext Just create a context object Multiple context objects can be created through this intermediate tool component,You only need to introduce the corresponding context objects in the parent and child components
6.props verification
Props of children attribute Represents the child node of the component label,When a component label has child nodes,props There will be this attribute children Properties and common props equally,Value can be any value(Text react Elements, components, and even functions) function Hello(props) { return ( <div> Child nodes of components:{props.children} </div> ) } <Hello>I am a child node</Hello>
Props test For components,props It's foreign,There is no guarantee what format of data is passed in by the component consumer,Simply put, the component caller may not know what data the component wrapper needs If the incoming data is incorrect,May cause error reporting key problem:The user of the component does not know what data needs to be passed props test:Allow when creating components,appoint props Type and format of App.propTypes = { colors:propTypes.array } effect:Capture when using components because props Error caused by,Give clear error prompt,Increase the robustness of components
- Class component
App.js import React,{ Component } from 'react' import PropsCheckRcc from './components/PropsCheckRcc.js' export default class APP extends Component{ render() { return ( <div> <PropsCheckRcc title={2}> <div>I am a stateful content<span>ha-ha</span></div> </PropsCheckRcc> </div> ); } } PropsCheckRcc.js import React,{ Component } from 'react' import PropTypes from 'prop-types' export default class PropsCheckRcc extends Component{ static propTypes = { title: PropTypes.string, children: PropTypes.object } render() { return ( <div> Stateful component --- {this.props.title} <br/> Stateful component --- {this.props.children} </div> ); } }
introduce PropTypes definition props check static propTypes = { title: PropTypes.string, children: PropTypes.object } Pay attention to the difference between two different propsTypes PropsTypes The former is built-in and the latter is introduced
- Function component
App.js import React,{ Component } from 'react' import PropsCheckRfc from './components/PropsCheckRfc.js' export default class APP extends Component{ render() { return ( <div> <PropsCheckRfc title={2}> <div>I am stateless content<span>ha-ha</span></div> </PropsCheckRfc> </div> ); } } PropsCheckRfc.js import React from 'react' import propTypes from 'prop-types' export default function PropsCheckRfc(props){ return ( <div> Stateless component --- {props.title} <br/> {/* props.children Get all child elements under the component */} Stateless component --- {props.children} </div> ); } PropsCheckRfc.propTypes = { title:propTypes.string, children:propTypes.object }
Receive after packaging props Components in import introduce propTypes import propTypes from 'prop-types' PropsCheckRfc.propTypes = { title:propTypes.string, children:propTypes.object } By overriding the of a component propTypes Object to achieve writing props Verification effect If it is verification children,If yes div For tag structures other than pure strings object type Fail props A warning will be prompted on the console during verification,Not mistakes
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-39tzsbcb-163404946103) (C: \ users \ Qifen \ appdata \ roaming \ typora \ user images \ image-20210923180441680. PNG)]
7.props default
scene:Paging component -> Number of displays per page, And props The verification method is similar, but there is no need to introduce a third-party plug-in to verify that propTypes The default value is defaultProps And props Verification can improve the robustness of the code
App.js import React,{ Component } from 'react' import DefaultPropsRcc from './components/DefaultPropsRcc.js' import DefaultPropsRfc from './components/DefaultPropsRfc.js' export default class APP extends Component{ state = { count:0 } render() { return ( <div> <DefaultPropsRcc title='I'm the title of the stateful component'>I am the child element of the stateful component passed over</DefaultPropsRcc> <DefaultPropsRfc title='I'm the title of the stateless component'>I am the child element of the passed stateless component</DefaultPropsRfc> </div> ); } }
- Class component
import React,{ Component } from 'react' export default class DefaultPropsRcc extends Component{ static defaultProps = { title:'I am the default stateful component title', children:'I am the default stateful component child element' } render() { return ( <div> Stateful component --- {this.props.title} <br/> Stateful component --- {this.props.children} </div> ); } }
- Function component
import React from 'react' export default function DefaultPropsRfc(props){ return ( <div> Stateless component --- {props.title} <br/> {/* props.children Get all child elements under the component */} Stateless component --- {props.children} </div> ); } DefaultPropsRfc.defaultProps = { title:'I am the default stateless component title', children:'I am the default stateless component child element' }
When props When no value is transferred,Exhibition defaultProps Default value for,It will be displayed when transferring values props Transmitted value props Value transmission priority> defaultProps Default value defaultProps Default values and propTypes The combination of verification can make your component code more robust
8, React lifecycle
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-9epvysdl-1634049746103) (C: \ users \ Qifen \ appdata \ roaming \ typora \ typora user images \ image-20210924105813858. PNG)]
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-wl5htjyy-163404946104) (C: \ users \ Qifen \ appdata \ roaming \ typora \ user images \ image-20210924105743453. PNG)]
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-sjpudi4v-163404946104) (C: \ users \ Qifen \ appdata \ roaming \ typora user images \ image-20210924110737484. PNG)]
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-n3famptu-1634049746105) (C: \ users \ Qifen \ appdata \ roaming \ typora \ user images \ image-20210924110847276. PNG)]
Find another tutorial
9, React network request (axios)
Go and have a look when you have time
10, Render props mode
React Overview of component reuse reflection:If some of the functions of the two components are similar or the same,How to deal with it? Treatment method:Reuse similar functions Reuse what? state operation state Method of Two ways: render props pattern High order component (HOC) be careful:These two methods are not new API,But use React Coding skills of its own characteristics,A fixed pattern evolved
Train of thought analysis thinking:To be reused state And operation state The method is encapsulated in a component How do I get the information reused in this component state In using components,Add a function whose value is prop,Get through function parameters <Mouse render={(mouse) => {}}/> How to render to any UI Use the return value of this function as the value to render UI content
day01 myself
// The following variables when rendering in ReactDOM.render are not bidirectional data streams, but unidirectional data streams? So it's only useful for the first time, and it won't change later? // setInterval(()=>{ // isloading = !isloading; // console.log(isloading); // },100) <div>{isloading ? 'loading...':'done'}</div> react Conditional rendering only dom Tree change,Redrawn unlike vue yes v-show wxapp yes wx-hidden react You also need to have a root element wrapped,vue Can use<template></template>Use only to wrap labels that are not actually rendered react Zhongwei<></> react There are no instructions for list rendering in(vue v-for) Only higher order functions can be used(for example map Function to traverse the rendering list) <div>{list.map(item=>{ return <p key={item.id}>{item.id} ----> {item.name}</p> })}</div> vue Medium:key="xx" stay react As shown in key={xx} Four event bindings can be obtained state Method of Li value + First kind:adopt bind change this point react object + Second:Point to the context object by using the arrow function(react object ) Here, the function call needs to be added() + Third:Use in constructors bind change this Direction of(The third needs to be combined constructor Constructor) + Fourth:Define the function as an arrow function + The third is recommended/Fourth react in jsx take state Values in ps:<div>{this.state.msg}</div> this.setState Is an asynchronous request that implements two-way binding,So we need to use the following two ways to achieve something similar to wxapp // The first asynchronous method uses the callback function in the setState method to realize asynchronous call // The second is asynchronous. async await is recommended Controlled and uncontrolled components(be used for ref) The difference between the two methods 1.Data binding the first data binding is ref="inputRef" The second is ref={this.inputRef} 2.The first type of constructor does not need to go to the constructor, and the second type needs to be in the react in import introduce createRef Method in constructor this.inputRef = createRef() Initialize a variable by createRef()method 3.obtain ref Object first this.refs.inputRef Second this.inputRef.current 4.The first is 16.3 The second version is the new version
day02 myself
vue Custom components need to be defined,register,Render and React Just define,Render,No registration required The internal component cannot control or modify the external incoming props React Hook "useContext" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function react-hooks/rules-of-hooks *****************Context Value Passing Provider of value It can transmit not only data but also methods,object******************** useContext etc. hooks Can only be used in React In function component React Everything is a component Typo in static class property declaration react/no-typos assembly.propTypes It must be lowercase,Others can be written in uppercase PropTypes ***********************************propTypes instead of PropTypes The initial is not capitalized********************** When props When no value is transferred,Exhibition defaultProps Default value for,It will be displayed when transferring values props Transmitted value props Value transmission priority> defaultProps Default value
Miscellaneous notes
1. Difference between export and export default
2.base64 format picture
data:image/png;base64,base64 Coded png Picture data
<bind name="lang" value="@io.choerodon.mybatis.helper.LanguageHelper@language()"/> <bind name="tenantId" value="@io.choerodon.core.oauth.DetailsHelper@getUserDetails().getTenantId()"/> select cast(lzpet.PRODUCTION_EQUIPMENT_TABLE_ID as char) PRODUCTION_EQUIPMENT_TABLE_ID, cast(lzpet .PRODUCTION_EQUIPMENT_ID as char) PRODUCTION_EQUIPMENT_ID, lzpet .PRODUCTION_EQUIPMENT_CODE, cast(lzpet .EQUIPMENT_ID as char) EQUIPMENT_ID, lzpet .EQUIPMENT_CODE , lzpet .EQUIPMENT_NAME , cast(le.PROD_LINE_ID as char) PROD_LINE_ID, le.PROD_LINE_CODE from hlos_wms.lwms_zhenyu_production_equipment_table lzpet left join hlos_mds.lmds_equipment le on le.equipment_id=lzpet .EQUIPMENT_ID where lzpet .TENANT_ID =155 <if test="equipmentId!=null"> and lzpet .EQUIPMENT_ID =#{equipmentId} </if> <if test="equipmentCode!=null"> and lzpet .EQUIPMENT_CODE =#{equipmentCode} </if> <if test="productionEquipmentCode!=null"> and lzpet .PRODUCTION_EQUIPMENT_CODE =#{productionEquipmentCode} </if> <if test="equipmentName!=null"> <bind name="equipmentName" value="'%' + equipmentName + '%'"/> and lzpet .EQUIPMENT_NAME like #{equipmentName} </if> LMDS.EQUIPMENT_PRODUCT LWMS.ZY_EQUIPMENT_TABLE