react component communication

Keywords: Javascript Front-end React

react introduction and installation

Chinese website: https://react.docschina.org/

Official website: https://reactjs.org/

introduce

1.react Is used to build web User interface.
2.Throughout react Almost all of them are used JavaScript Code development .
3.react It can scale freely in front of a class library or an entire framework.
4.author:By Facebook The company's front-end development team develops and maintains

advantage

  • Everything is a component
stay react Project development in progress,Encapsulation of functions using components
  • Fast speed
stay react Zhonggong adopts virtual DOM mechanism,Not directly to reality DOM Operate.
  • Cross browser compatibility
Use virtual DOM mechanism,Do not operate directly from the browser,Even in IE8 Can be used in
  • Isomorphic, pure javascript
stay react It is almost always used in project development JavaScript
  • Unidirectional data flow
stay react Two architectures are provided in: flux and redux To realize one-way data flow

shortcoming

  • react is not a complete framework
  • If you want to develop a complete project, you need to combine reactRouter and redux to build it

Download and install (Class Library)

  • cdn
development environment :
<script src="https://cdn.bootcdn.net/ajax/libs/react/18.0.0-alpha-6f3fcbd6f-20210730/cjs/react.development.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/react-dom/18.0.0-alpha-6f3fcbd6f-20210730/cjs/react-dom.development.js"></script>
Production environment:
take development Change to production
  • npm
cnpm i react react-dom -S

Problems solved by react

  • Componentization: use componentization for development, making the code easy to read and maintain
  • Development efficiency: use components to modularize the code, which makes the development speed very fast and easy to maintain
  • Running efficiency: use the virtual DOM mechanism to run fast
  • Maintenance: the use of componentization and redux makes the code easy to maintain and handle, and complex businesses easy to operate
  • User experience: the user experience is better and SPA application is adopted

Scaffold installation and use

Global installation scaffold

npm  i -g create-react-app   #Global installation scaffold
create-react-app		-V				#View version

Initialize project

create-react-app   entry name			#Create phase

Startup item

cd my-app		#Enter project
npm start		#Start project
 The default project runs on: http://localhost:3000

Modify port number

  • package.json
"start": "set PORT=5000 && react-scripts start",
  • node_modules/react-scripts/scripts/start.js
const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000;

Project directory introduction

my-app
	-node_modules			#Dependent package
  -public					
					index.html		#Unique page for the project
  -src	
					App.css					#The style of the root component 
					App.js					#Root component
					App.text.js			#Root component test file
					index.css				#Entry file style
					index.js				#Project entry file
  package.json					#Project basic information and dependent package version
  package-lock.json			#Project basic information, dependency details and locked version
  READ.me								#Introduction to relevant instructions

jsx template syntax

jSX:javascript  XML,stay js Using extensible markup language in(xml)
html:Label attribute text  (Fixed writing)
xml:Label attribute text  (The above three can be customized)
jsx Template syntax
1.Labels can be customized
2.Label structure must have start and end characters
3.The label structure can be single label or double label
4.xml The syntax is strictly case sensitive
Install plug-ins:
ES7 React/Redux/GraphQL/React-Native snippets

jsx annotation syntax

 {/* jsx Comments for the template */}
control+/

Data rendering

import React from 'react'
let name = 'zs';
let age  = 18;
export default function Data() {
    return (
        <div>
            <h1>Data rendering </h1>
            {/* Data rendering: using {}, you can write js syntax directly in {}*/}
            <h2>{name}</h2>
            <div>{name+'Hello'}</div>
            <div>{1+1}</div>
            <div>{age >= 18 ? 'Adult' : 'under age'}</div>
        </div>
    )
}

Property binding

import React from 'react'
let url = 'http://www.jd.com'
export default function Attr() {
    return (
        <div>
            {/* Property binding */}
             {/* Custom attribute binding */}
            <a href={url} a={10}>JD.COM</a>
        </div>
    )
}

Output of arrays and objects

import React from 'react'
// array
let arr = ['Kung Pao Chicken','Fermented glutinous rice soup','Chinese hamburger','Cold Rice Noodles'];
// object
let person = {
    name:'zs',
    age:30,
    girlfriend:'ls',
}
//  Array object
let brand =  [
    {id:1,name:'LV'},
    {id:2,name:'Dior'},
    {id:3,name:'Lamborghini'},
]

export default function Arr() {
    return (
        <div>
  			  {/* It cannot be rendered directly, but can only be converted to string rendering */}
            <div>{JSON.stringify(arr)}</div>
            <div>{JSON.stringify(person)}</div>
            <div>{JSON.stringify(brand)}</div>
        </div>
    )
}

conditional rendering

  • if structure cannot be used in jsx template syntax, only ternary operator can be used

List rendering

Traversal array:forEach  map
                forEach:no return value
                1.map:There is a return value
                2.A unique must be bound on the direct child element of the traversal key
                3.key Value can only be Number perhaps String
import React from 'react'
let arr = ['Wang Minyu','Wu Jianji','Zhang Chenyang','Wu Jijian']; 

export default function List() {
    return (
        <div>
            <ul>
                {arr.map(item=
                 {/* Return is omitted here. When the value of return is multiple lines of code, it is enclosed in parentheses */}
                         (<li key={item}>{item}</li>)
                    )}
            </ul>
        </div>
    )
}

Style dynamic style

import React from 'react'
let name = "zs";
export default function Style() {
    return (
        <div>
            <h2>style style</h2>
            {/* Inline style cannot be used in jsx template syntax */}
            {/* <div style="background:pink;">{name}</div> */}

            {/* 
                When using inline style, it needs to be written dynamically 
                1.style Double layer {}
                2.Outer layer {}: jsx template syntax
                3.Inner layers {}: objects
            */}
            <div style={{background:'pink'}}>{name}</div>
        </div>
    )
}

className dynamic class name

stay jsx The class name used in the template syntax is:className
import React from 'react'
import './style.css'
let name = "Wang Minyu";
export default function Style() {
    return (
        <div>
            {/* The class name used in jsx template syntax is: className */}
            <div className="box"></div>
        </div>
    )
}

Rich text rendering

  • Dangerouslysetinnerhtml = {_html: variable name}}
import React from 'react'
let str = `
        <div>
        <ul>
            <li>🍗</li>
            <li>Duck leg</li>
            <li>Ham</li>
            <li>pig 's trotters</li>
        </ul>
</div>
`;
export default function Style() {
    return (
        <div>
             {/* Similar to parsing html */}
            <div dangerouslySetInnerHTML={{__html:str}}></div> 
        </div>
    )
}

summary

jsx Template syntax:
1.Must have in component return
2.jsx There must be a root node in the template syntax
3.stay jsx Writing in template grammar xml Grammatical structure
4.stay jsx Template syntax needs to be strictly case sensitive
5.stay jsx Tags in template syntax must have start and end characters
6.stay jsx Template syntax,When encountered<>Time,treat as HTML To analyze,When encountered{}treat as jsx Template syntax to parse

assembly

Function component

  • Declared with function, the function name must be capitalized
  • In the form of anonymous function assignment.
  • There must be a return in the function component
  • There must be only one root node in the function
import React from 'react'
export default function Child(props) {
    console.log(props);
    return (
        <div>
        </div>
    )
}
import React from 'react'
const Child = (props)=> {
    console.log(props);
    return (
        <div>	
        </div>
    )
}
 export default Child;

Class component

 * Class component
 * 1.Class components use keywords class Make a statement
 * 2.Class names must be capitalized
 * 3.Class components must inherit from the base class React.Component
 * 4.Class component must have render method
 * 5.stay render Method must have return
 * 6.stay render Method must have a root node

Differences between function components and class components

Class component: have state State machine and hook function
 Function component:No, state State machine and hook function ,  Function components are more efficient than class components

Event binding plus parameters

Event binding syntax:

onClick={Event function}
 <button onClick={this.handler}>click</button>
{/* <button onClick={this.handler()}>Click 1 < / button > */}
  • You cannot add () directly after an event function. Adding () directly is equivalent to calling directly

bind binding event

<button onClick={this.send.bind(this,20)}>bind Binding event</button>
import React, { Component } from 'react'
export default class Event extends Component {
    name = 'zs';
    render() {
        return (
            <div>
                {/* bind Binding event */}
                <button onClick={this.send.bind(this,20)}>bind Binding event</button>
            </div>
        )
    }
    handler(){
        console.log(this);//this points to window, and the strict mode is undefind
        console.log('Triggered');
    }

    send(age,e){
        console.log(this.name);
        console.log(age);
        console.log(e);//If passed implicitly (no event object argument), it is received at the last formal parameter.
    }
}

Arrow function binding event

<button onClick={(e)=>this.send1(e,'zs')}>click</button>
<button onClick={(e)=>{return this.send1(e,'zs')}}>click</button>
import React, { Component } from 'react'
export default class Event extends Component {
    name = 'zs';
    render() {
        return (
            <div >
                {/* Arrow function binding event */}
                <button onClick={(e)=>
            			//Use an arrow callback. The callback value is this method. Omit return.
            		this.send1(e,'Xiao Hong')}>Arrow function binding event</button>
                <button onClick={(e)=>{
                        //Use an arrow callback to execute this method in the callback
                  return this.send1(e,'zs')}}>click</button>
            </div>
        )
    }
    send1(e,name){
        console.log(this);//The arrow callback has no this, so it gets this in the scope (Event)
        console.log(e);//The event object in the formal parameters of the callback is consistent with the event object of the native event.
        console.log(name);
    }
}

Get event object

  • bind parameter passing: it is implicitly passed (no event object argument), which is received at the last formal parameter of the method.
  • Arrow callback: the event object is consistent with the event object of the native event in the formal parameters of the callback.

Block default + Bubble + capture

Block default events

e.preventDefault()
import React, { Component } from 'react'
import './stop.css'
export default class Stop extends Component {
    render() {
        return (
            <div>
                <h2>Block default events</h2>
                <a onClick={(e)=>this.stop(e)} href="http://Www.tmall.com "> tmall</a>
                <div onContextMenu={(e)=>this.stop(e)} className="box"></div>
            </div>
        )
    }
    stop(e){
        e.preventDefault()
    }
}

Prevent event bubbling

 e.stopPropagation()
import React, { Component } from 'react'
import './stop.css'
export default class Stop extends Component {
    render() {
        return (
            <div>   
                <div className="outer" onClick={()=>this.outer()}>
                    <div className="inner" onClick={(e)=>this.inner(e)}></div>
                </div>
            </div>
        )
    }

    outer(){
        console.log('outer');
    }
    inner(e){
        // Prevent event bubbling
        e.stopPropagation()
        console.log('inner');
    }
}

Event capture

onClickCapture={}
import React, { Component } from 'react'
import './stop.css'
export default class Stop extends Component {
    render() {
        return (
            <div>
                {/* Capture events */}
                <div className="outer" onClickCapture={()=>this.outer()}>
                    <div className="inner" onClickCapture={()=>this.inner()}></div>
                </div>
            </div>
        )
    }
    outer(){
        console.log('outer');
    }
    inner(){
        console.log('inner');
    }
}

state machine

  • For use in class components only

this.setState()

this.setState({Key to modify data:'Modified data'},callback)//The first parameter is an object. Although an object is passed, it will only modify the value of this.state and will not be overwritten.
  • The only way to modify the data in the state machine is this.setState()

  • The setState method is an asynchronous processing function

state is declared as a property

state

import React, { Component } from 'react'
export default class Index extends Component {
    // Only properties declared in the state machine can be rendered to the page at update time
    name:'zs'
    state = {
        name:'zs',
        age:18
    }
    render() {
        return (
            <div>
                <h2>name The value of is:{this.state.name}</h2>
                <button onClick={()=>this.changeName('ls')}>Wang Cuihua</button>
            </div>
        )
    }
    changeName(name){
        // this.name = name;
        // console.log(this.name); / / the data is changed, but it will not be rendered to the view again.
        // this.state.name = name;
        // console.log(this.state.name); / / the data is changed, but it will not be rendered to the view again.
        this.setState({name},()=>{
         console.log(this.state);//Although an object is passed, it will only modify the value of this.state without overwriting it.
        })
    }
}

state machine declared in constructor

import React, { Component } from 'react'
export default class Index extends Component {
    constructor(){
        super();//The constructor of an inherited class must have super
        this.state =  {
            name:'zs',
        }
    }
    render() {
        return (
            <div>
                <h2>name The value of is:{this.state.name}</h2>
                <button onClick={()=>this.changeName('Wang Cuihua')}>Wang Cuihua</button>
            </div>
        )
    }
    changeName(name){
        this.setState({name},()=>{
          console.log(this.state.name);//Although an object is passed, it will only modify the value of this.state without overwriting it.
        })
       
    }
}

Component communication

Father to son

Class component

  • Parent component: pass data to child components through custom attributes
  • Subcomponent: receive data through this.props
Parent component
import React from 'react'
import Child from './Child'
export default class User extends React.Component{
    constructor(){
        super()
        this.state = {
          title : 'Wu Jing congratulations to Wu Jing';
        }
    }
    render(){
        // Destructuring assignment 
        const {title} = this.state
        return (
            <div className="alert  alert-info">
                {/*Pass data through custom attributes*/}
                <Child title={title}  />
            </div>
        )
    }
}   
import React, { Component } from 'react'
export default class Child extends Component {
    render() {
        // console.log(this.props);// This is an object.
        const {title} = this.props;
        return (
            <div className="well">
                <div>Hot news:{title}</div>
            </div>
        )
    }
}

Function component

  • Parent component: passing data through custom attributes
  • Subcomponent: accept data through formal parameter props. Props is an object.
import Child from './Child'
let name=  'zs';
export default function Fun(){
    return  (
        <div className="alert alert-info">
            <Child name={name} />
        </div>
    )
}
import React from 'react'
export default function Child(props) {
    console.log(props);
    return (
        <div className="well">
            <div>name The value of is:{props.name}</div>
        </div>
    )
}

Son to father

Class component

  • Parent component: pass methods to child components through custom events
  • Subcomponent: receive the passed method through this.props, trigger the event, call the method, and pass the data in the form of parameters of the method.
  • Parent component: the user-defined event triggers the execution of the callback function, and the formal parameter in the callback receives the data from the child.
import React, { Component } from 'react'
import Child from './Child'
export default class Parent extends Component {
    render(){
        // Destructuring assignment 
        const {title} = this.state
        return (
            <div className="alert  alert-info">
                {/*Passing methods through custom events*/}
                <Child onDel={(index)=>this.delItem(index)} />
            </div>
        )
    }
    delItem(index){
        log(index);
    }
}

import React, { Component } from 'react'
export default class Child extends Component {
    render() {
        // Destructuring assignment 
        const {onDel} = this.props;
        return (
        <div className="well">
     	 <button  onClick={()=>onDel(111)}>delete</button>         
         {/*When there is no assignment deconstruction*/}
		<button  onClick={()=>this.del(111)}>delete</button>    
            </div>
        )
    }
     del(index){
         this.props.onDel(index)
     }
}

Function component

  • Same as class components.
import Child from './Child'
export default function Fun(){
    return  (
        <div className="alert alert-info">
            <Child change={(name)=>change(name))} />
        </div>
    )
    const change = (name)=>{
        log(name);
    }
}
import React from 'react'
export default function Child(props) {
  const {change} = props;
    return (
        <div className="well">
            <div onClick={()=>change('zs')}>name The value of becomes zs</div>
        </div>
    )
}

Interview questions

⚫ React What are the advantages and disadvantages?
⚫ React What problems have been solved?
⚫ React,vue,angular What's the difference?? 
⚫ JSX What is it??How does the browser parse JSX? 
⚫ react Components come in several ways,What's the difference? 
⚫ state How to set the initial value and change it? 
⚫ React How to bind events in?

Posted by ReDucTor on Fri, 03 Dec 2021 07:37:36 -0800