preface

React is one of the top three frameworks on the front end and a skill in development; This article summarizes some skills and skills of React development from the actual development, which is suitable for students who are beginners or have certain project experience.

The source address

Please poke, welcome star

rendering

1 Component Communication

1.1 props

Child components

import React from "react";
import PropTypes from "prop-types";
import { Button } from "antd";

exportDefault class EightteenChildOne extends React.Com {static propTypes = {//propTypes} PropTypes.string }; Click () = = > {/ / father son pass by triggering method. This props. EightteenChildOneToFather ("This is props changing the value of the parent element.");
  };

  render() {
    return<div> <div> This is the value passed in by props {this.props. Name}</div> <Buttontype="primary"OnClick ={this.click}> </Button> < div>); }}Copy the code

The parent component

<EightteenChildOne name={'props props name '} eightteenChildOneToFather = {(mode) = > enclosing eightteenChildOneToFather (mode)} > < / EightteenChildOne > / / or < EightteenChildOne  name={'props props name '} eightteenChildOneToFather={this.eightteenChildOneToFather.bind(this)}></EightteenChildOne> 
Copy the code

Props for passing multiple values: traditional

const {dataOne,dataTwo,dataThree} = this.state
<Com dataOne={dataOne} dataTwo={dataTwo} dataThree={dataThree}>
Copy the code

Upgrade the writing

<Com {... {dataOne,dataTwo,dataThree}}>Copy the code

1.2 Props

Principle: child components inside use props for the parent component method called directly, which changes the value of the parent component note: this method and props, is the application of the props, so there is no example in source

Call the parent component method to change the value

State = {count: {}} changeParentState = obj => {this.setstate (obj); } / / subcomponents onClick = () = > {this. Props. ChangeParentState ({count: 2}); }Copy the code

1.3 the Provider, the Consumer and the Context

1.Context before 16.x defines a global object, similar to vue’s eventBus. If a component wants to use this value, it will get it directly from this

Class MessageList extends React.Component {getChildContext() {
    return {color: "purple",text: "item text"};
  }

  render() {
    const {messages} = this.props || {}
    const children = messages && messages.map((message) =>
      <Message text={message.text} />
    );
    return<div>{children}</div>; } } MessageList.childContextTypes = { color: React.PropTypes.string text: React.PropTypes.string }; Class Message extends React.Component {render() {
    return( <div> <MessageItem /> <Button>Delete</Button> </div> ); } class MessageItem extends react.component.extends {MessageItem extends react.component.extends {MessageItem extends react.component.extends {MessageItem extends react.component.extends}render() {
    return( <div> {this.context.text} </div> ); }} messageItem.contexttypes = {text: react.proptypes. String // React.proptypes was rejected in 15.5, see the actual React version}; class Button extends React.Component {render() {
    return (
      <button style={{background: this.context.color}}>
        {this.props.children}
      </button>
    );
  }
}

Button.contextTypes = {
  color: React.PropTypes.string
};
Copy the code

Context after 2.16.x uses Provider and Customer mode, passing value in the top-level Provider, obtaining the value in the descendant Consumer, and passing function. To modify the context declaration a global context definition,context.js

import React from 'react'
let{ Consumer, Provider } = React.createContext(); // Create context and expose Consumer and Provider patternsexport {
    Consumer,
    Provider
}
Copy the code

Parent Component Import

// Import Provider import {Provider} from".. /.. /utils/context"

<Provider value={name}>
  <div style={{border:'1px solid red',width:'30%',margin:'50px auto',textAlign:'center'}}> <p> Value defined by parent component :{name}</p> <EightteenChildTwo></EightteenChildTwo> </div> </Provider>Copy the code

Child components

// Import Consumer import {Consumer} from".. /.. /utils/context"
function Son(props) {
  return<div style={{border: {border: 0; border: 0; border: 0;"1px solid blue",
            width: "60%",
            margin: "20px auto",
            textAlign: "center"}} > // In Consumer, you can get the value of the parent component directly by name <p> child component. </p> </div>)} </Consumer>); }export default Son;
Copy the code

1.4 EventEmitter

The EventEmiter portal uses the Events plug-in to define a global event mechanism

1.5 Route transmission Parameters

1.params

<Route path='/path/:name' component={Path}/>
<link to="/path/2">xxx</Link>
this.props.history.push({pathname:"/path/"+ name}); Reads the parameters with: this props. Match. Params. NameCopy the code

2.query

<Route path='/query' component={Query}/>
<Link to={{ pathname : '/query' , query : { name : 'sunny' }}}>
this.props.history.push({pathname:"/query",query: { name : 'sunny'}}); Read parameters with: this props. Location. Query. NameCopy the code

3.state

<Route path='/sort ' component={Sort}/>
<Link to={{ pathname : '/sort ' , state : { name : 'sunny' }}}> 
this.props.history.push({pathname:"/sort ",state : { name : 'sunny'}}); Read parameters with: this props. Location. Query. The stateCopy the code

4.search

<Route path='/web/search ' component={Search}/>
<link to="web/search? id=12121212">xxx</Link> this.props.history.push({pathname:`/web/search? id${row.id}`}); Read parameters with: this props. The location. The searchCopy the code

This is a bug in react-router-dom: v4.2.2. The react-router-dom: v4.2.2 has a bug in the react-router-dom: v4.2.2

5. The advantages and disadvantages

1. Params refreshes page parameters in HashRouter and BrowserRouter routes without losing 2. State Refreshes page parameters in BrowserRouter routes without losing 3. Refresh page parameters in HashRouter and BrowserRouter routes. 4. Query and state can pass objectsCopy the code

1.6 onRef

How it works :onRef communicates by passing this(the component instance) as an argument to the parent component using the props event mechanism. Then the parent component can manipulate the state and methods of the child component

EightteenChildFour.jsx

export default class EightteenChildFour extends React.Component {
  state={
      name:'This is the name value of the component EightteenChildFour.'
  }

  componentDidMount(){this.props. OnRef (this) console.log(this) // -> EightteenChildFour is passed to the parent this.props. OnRef () method} click = () => {this.props. this.setState({name:'This is the name value that the component click method EightteenChildFour changes.'})};render() {
    return (
      <div>
        <div>{this.state.name}</div>
        <Button type="primary"OnClick ={this.click}> </Button> </div>); }}Copy the code

eighteen.jsx

<EightteenChildFour onRef={this.eightteenChildFourRef}></EightteenChildFour>

eightteenChildFourRef = (ref)=>{
  console.log('The value eightteenChildFour is Ref'Console.log (ref) // call the subcomponent method ref.click()}Copy the code

1.7 ref

How it works: Obtain the entire subcomponent instance from the React ref property and then operate on it

EightteenChildFive.jsx

// Common component definition methodsexport default class EightteenChildFive extends React.Component {
  state={
      name:'This is the name value of the component EightteenChildFive.'
  }

  click = () => {
    this.setState({name:'This is the name value that the component click method EightteenChildFive changes.'})};render() {
    return (
      <div>
        <div>{this.state.name}</div>
        <Button type="primary"OnClick ={this.click}> click to change the name value of the EightteenChildFive component </Button> </div>); }}Copy the code

eighteen.jsx

// The hook gets the instancecomponentDidMount(){
    console.log('The Ref value eightteenChildFive is'}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}"eightteenChildFiveRef"])} // The component defines an attribute <EightteenChildFive ref="eightteenChildFiveRef"></EightteenChildFive>
Copy the code

1.8 redux

Redux is a stand-alone event communication plugin, so I won’t go into detail here.

1.9 MobX

MobX is also a stand-alone event communication plugin, so I won’t go into too much detail here.

1.10 flux

Flux is also a stand-alone event communication plugin, so I won’t go into too much detail here.

1.11 hooks

1. Hooks communicate with userReducer and context. The following simulation implements a simple redux 2. Core files are divided into action, Reducer, and types action.js

import * as Types from './types';

export const onChangeCount = count => ({
    type: Types.EXAMPLE_TEST,
    count: count + 1
})
Copy the code

reducer.js

import * as Types from "./types";
export const defaultState = {
  count: 0
};
export default (state, action) => {
  switch (action.type) {
    case Types.EXAMPLE_TEST:
      return {
        ...state,
        count: action.count
      };
    default: {
      returnstate; }}};Copy the code

types.js

export const EXAMPLE_TEST = 'EXAMPLE_TEST';
Copy the code

eightteen.jsx

exportconst ExampleContext = React.createContext(null); // Create the createContext context // Define the componentfunction ReducerCom() {
  const [exampleState, exampleDispatch] = useReducer(example, defaultState);

  return (
    <ExampleContext.Provider
      value={{ exampleState, dispatch: exampleDispatch }}
    >
      <EightteenChildThree></EightteenChildThree>
    </ExampleContext.Provider>
  );
}
Copy the code

EightteenChildThree JSX / / component

import React, {  useEffect, useContext } from 'react';
import {Button} from 'antd'

import {onChangeCount} from '.. /.. /pages/TwoTen/store/action';
import { ExampleContext } from '.. /.. /pages/TwoTen/eighteen'; const Example = () => { const exampleContext = useContext(ExampleContext); UseEffect (() => {// listen for changes console.log('Change implemented')
    }, [exampleContext.exampleState.count]);

    return(< div > < p > value is {exampleContext. ExampleState. Count} < / p > < Button onClick = {() = > ExampleContext. Dispatch (onChangeCount (exampleContext. ExampleState. Count))} > click add 1 < / Button > < / div >)}export default Example;
Copy the code

3. Hooks encapsulate the React API, exposing hooks that are easy to use.

4. The hooks are:

The hook, role
useState Initialize and set the state
useEffect ComponentDidMount, componentDidUpdate, and componentWillUnmount are combined, so you can listen for changes in the useState definition
useContext Define a global object, similar to context
useReducer Enhancements can be made to provide redux-like functionality
useCallback Memory function, which takes two arguments, the first argument is an anonymous function, which is the body of the function we want to create. The second argument is an array of variables, each of which is used to determine whether the body of the function needs to be recreated. If the values of the variables passed remain the same, the result is returned. If any of these changes, the new result is returned
useMemo UseCallback returns a function,useDemo returns a value
useRef Gets the DOM corresponding to the ref attribute
useImperativeMethods Custom instance value exposed to parent component when using ref
useMutationEffect It has the same effect as useEffect, but is triggered synchronically at the same stage when React executes its DOM changes before updating its sibling component
useLayoutEffect This function is the same as useEffect, but is triggered synchronously after all DOM changes

5.useImperativeMethods

functionFancyInput(props, ref) { const inputRef = useRef(); useImperativeMethods(ref, () => ({ focus: () => { inputRef.current.focus(); }}));return<input ref={inputRef} ... / >; } FancyInput = forwardRef(FancyInput);Copy the code

1.12 slot.

A slot is used to pass labels from a parent component to a child component. This is similar to vUE’s V-slot scenario: some components share some DOM logic, and some of the dom logic is independent

// Import SlotChild from the parent component file'SlotChild'<SlotChild slot={<div> This is the parent component's slot</div>}> </SlotChild> // The child component can get the content directly by getting this.propsCopy the code

1.13 contrast

methods advantages disadvantages
props There is no need to introduce external plug-ins Sibling component communication needs to establish a common parent component, trouble
Props upgrade No need to import external plug-ins, children pass to the parent, do not need to use methods in the parent component to receive With the props
The Provider, the Consumer and the Context There is no need to introduce external plug-ins to communicate tools across multiple levels of components or sibling components Status data Status tracking trouble
EventEmitter Can support brother, father and son components communication You want to introduce an external plug-in
Routing and the cords Can support brother components to pass value, simple page data transfer is very convenient The parent and child components are unable to communicate
onRef You can get the entire child component instance in a simple way Brother component communication trouble, official do not recommend to use
ref With onRef With onRef
redux Established a global state manager, brother and son communication can be solved External plug-ins have been introduced
mobx Established a global state manager, brother and son communication can be solved External plug-ins have been introduced
flux Established a global state manager, brother and son communication can be solved External plug-ins have been introduced
hooks 16. X new property, can support sibling, father and son components communication You need to use it with context
slot Support tag passing from parent to child

Redux, Mobx, and Flux

methods introduce
redux 1. Core modules :Action,Reducer,Store; 2. Store and change logic are separate; 3. There is only one Store. 4. A single Store with layered Reducer. 5. No concept of scheduler; 6. Container components are related; 7. The state is immutable; 8. Follow more functional programming ideas
mobx 1. Core modules: Action, Reducer, Derivation; 2. Multiple stores; 3. The design is more object-oriented and responsive, usually wrapping state as observable objects that are automatically updated as they change
flux 1. Core modules: Store, ReduceStore, Container; 2. Multiple stores;

2.require.context()

This is the WebPack API, which is covered in the Vue Tips, because both vue and React projects are based on WebPack packaging, so it can be used in React as well

const path = require('path')
const files = require.context('@/components/home'.false, /\.vue$/)
const modules = {}
files.keys().forEach(key => {
  const name = path.basename(key, '.vue')
  modules[name] = files(key).default || files(key)
})

Copy the code

3.Decorator

Definition: Decorators are a new ES7 feature that modifies the properties of a class

import React from 'react'
import Test from '.. /.. /utils/decorators'@test // As long as the Decorator is followed by Class, the default is to pass the Class as an argument. class TwentyNine extends React.Component{componentDidMount(){
        console.log(this,'decorator.js') // whereup you are getting an example of the class console.log(whereup you are testable)}render() {return<div> this is technique 23</div>)}}export default TwentyNine
Copy the code

decorators.js

function testable(target) {
  console.log(target)
  target.isTestable = true;
  target.prototype.getDate = ()=>{
    console.log( new Date() )
  }
}

export default testable
Copy the code

Many middleware, such as Redux, encapsulate the use of decorators

4. Use the if… else

Scenario: Sometimes you need to display different content depending on the status value page

import React from "react";

export default class Four extends React.Component {
  state = {
    count: 1
  };
  render() {
    let info
    if(this.state.count===0){info=(<span> this is the number of 0 display </span>)}else if(this.state.count===1){info=(<span> this is the number of 1 displayed </span>)}return( <div> {info} </div> ); }}Copy the code

5. Five ways to change the state value

Method 1

let {count} = this.state
this.setState({count:2})
Copy the code

Method 2: callBack

this.setState(({count})=>({count:count+2}))
Copy the code

Method 3: Receives the state and props parameters

this.setState((state, props) => {
    return { count: state.count + props.step };
});
Copy the code

Pattern 4: hooks

const [count, setCount] = useState(0) // Set valuesetCount(count+2)
Copy the code

Method 5: Call after the state value is changed

This.setstate ({count:3},()=>{// get the result to do something})Copy the code

6. Listen for changes in states

Use componentWillReceiveProps before 1.16 x

componentWillReceiveProps (nextProps){
  if(this.props.visible ! == nextProps. Visible){//props changed to do something}}Copy the code

Note: in some cases componentWillReceiveProps also triggers in props value did not change, because for the first time in the life cycle of will not be called after the render, but could be invoked in each render after = when the parent component again send props

After 2.16 x use getDerivedStateFromProps, 16. After x componentWillReveiveProps also not remove

export default class Six extends React.Component {
  state = {
    countOne:1,
    changeFlag:' '
  };
  clickOne() {let {countOne} = this.state
    this.setState({countOne:countOne+1})
  };
  static getDerivedStateFromProps (nextProps){
    console.log('Change execution')
    return{
      changeFlag:'State value change execution'}}render() {
    const {countOne,changeFlag} = this.state
    return (
      <div>
        <div>
         <Button type="primary"OnClick ={this.clickone.bind (this)}> <span>countOne ={countOne}</span> <div>{changeFlag}</div> </div> ); }}Copy the code

7. Component definition methods

Method 1: Function definition in ES5

function FunCom(props){
  return<div> This is the component defined by Function </div>} ReactDOM"Sebastian"/>, mountNode) // This was the way to define stateless components before the hooks came out. Now you can handle state with hooksCopy the code

Method 2: ES5 createClass definition

const CreateClassCom = React.createClass({
  render: function() {
  return<div> This is the component defined by React. CreateClass </div>}});Copy the code

Method 3: EXTENDS of ES6

class Com extends React.Component {
  render() {return<div> this is the component defined by react.ponent </div>.Copy the code

call

export default class Seven extends React.Component {
  render() {
    return( <div> <FunCom></FunCom> <Com></Com> </div> ); }}Copy the code

ES5 createClass createClass createClass createClass createClass createClass Component created using the properties of the new class in ES6 This component is easy to create.

8. Get the Component from the REF property

Method 1: also the earliest use, this. Refs can also be applied to components to get the component instance

class RefOne extends React.Component{
  componentDidMount() {
    this.refs['box'].innerHTML='Here's the div box, get it by ref.'
  }
  render() {return(
      <div ref="box"></div>
    )
  }
}
Copy the code

Method 2: the callback function, which mounts a function on a DOM node or component and takes an instance of the DOM node or component as its input, achieves the same effect as the string form, which is to get a reference to it

class RefTwo extends React.Component{
  componentDidMount() {
    this.input.value='This is the default value for the input box.';
    this.input.focus();
  }
  render() {return( <input ref={comp => { this.input = comp; }}}} / >)Copy the code

Use this method to create a ref after React version 16.3. Assign it to a variable mounted on a DOM node or component via ref. The current property of the REF will fetch an instance of the DOM node or component

class RefThree extends React.Component{
  constructor(props){
    super(props);
    this.myRef=React.createRef();
  }
  componentDidMount(){
    console.log(this.myRef.current);
  }
  render() {return <input ref={this.myRef}/>
  }
}
Copy the code

This can be used to create subcomponents to pass the ref. ForwardRef React

class RefFour extends React.Component{
  constructor(props){
    super(props);
    this.myFourRef=React.forwardRef();
  }
  componentDidMount(){
    console.log(this.myFourRef.current);
  }
  render() {return <Child ref={this.myFourRef}/>
  }
}
Copy the code

The child component is created by the React. ForwardRef, which passes the ref to the internal node or component to enable cross-level references. ForwardRef can now retrieve the original component instance in the higher-order component. This feature will be highlighted in Tip 18

9. The static use

Scenario: A keyword that declares a static method that can be called directly even if there is no component instance

export default class Nine extends React.Component {
  static update(data) {
    console.log('Static method call executed')}render() {
    return(<div> this is the static keyword skill </div>); } } Nine.update('2')
Copy the code

Note: 1.ES6 class: when we define a component, we usually define a class. Static creates a property or method 2 that belongs to the class. The component is an instance of this class. The props and state of the Component belong to this instance, so the instance has not yet been created. So the static and not react to define, and combined with the static keyword, said this method will not be instance inheritance, but directly through the class to call, so also is unable to access to this 4. GetDerivedStateFromProps also by static method to monitor value, see skills 6

10. The constructor and super

Review: 1. Before we talk about these two properties, let’s review ES6 function definition method 2. 3. The super keyword is used to access and call a function on an object’s parent object

export default class Ten extends React.Component {
  constructor() {/ / class the main function of the super () / / React.Com ponent. Prototype. The constructor. The call (this), is to get the properties and methods of the parent class. This state = {arr: []}}render() {
    return"> <div style =" text-align: center; }}Copy the code

11.PropTypes

Check that PropTypes have been deprecated since React V15.5. Use prop-types in way 1: the old way

class PropTypeOne extends React.Component {
  render() {
    return( <div> <div>{this.props.email}</div> <div>{this.props.name}</div> </div> ); }} PropTypeOne. PropTypes = {name: propTypes. String, / / value can be as an array, bool, func, number, object, symbol of email:function(props, propName, componentName) {// custom validatesif (
      !/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/.test(
        props[propName]
      )
    ) {
      return new Error(
        "Component" + componentName + "Properties in" + propName + "Does not match the mailbox format"); }}};Copy the code

Method 2: Use ES7’s static property keyword static

class PropTypeTwo extends React.Component {
  static propTypes = {
      name:PropTypes.string
  };
  render() {
    return( <div> <div>{this.props.name}</div> </div> ); }}Copy the code

12. Declare syntax using class fields

Scenario: You can initialize local state without constructors and declare class methods by using arrow functions without additional binding to them

class Counter extends Component {
  state = { value: 0 };

  handleIncrement = () => {
    this.setState(prevState => ({
      value: prevState.value + 1
    }));
  };

  handleDecrement = () => {
    this.setState(prevState => ({
      value: prevState.value - 1
    }));
  };

  render() {
    return (
      <div>
        {this.state.value}

        <button onClick={this.handleIncrement}>+</button>
        <button onClick={this.handleDecrement}>-</button>
      </div>
    )
  }
}
Copy the code

13. Asynchronous components

1. Scenario: Route switchover. If multiple page routes are loaded at the same time, it will be slow

2. Core API: loader: indicates the components to be loaded. Loading: indicates the components that are not loaded

3. Install the React-loadable Babel plug-in and install the syntact-dynamic-import. React-loadable is implemented with the asynchronous import of WebPack

const Loading = () => {
  return <div>loading</div>;
};

const LoadableComponent = Loadable({
  loader: () => import(".. /.. /components/TwoTen/thirteen"),
  loading: Loading
});

export default class Thirteen extends React.Component {
  render() {
    return<LoadableComponent></LoadableComponent>; }}Copy the code

4. Loadable.map () loads higher-order components of multiple resources in parallel

14. Dynamic components

Scenario: Dynamic component loading is involved when making a TAB switch, essentially using a ternary expression to determine whether the component is displayed

class FourteenChildOne extends React.Component {
    render() {
        return<div> This is dynamic component 1</div>; } } class FourteenChildTwo extends React.Component {render() {
        return<div> This is dynamic component 2</div>; }}export default class Fourteen extends React.Component {
  state={
      oneShowFlag:true} tab=()=>{ this.setState({oneShowFlag:! this.state.oneShowFlag}) }render() {
    const {oneShowFlag} = this.state
    return (<div>
        <Button type="primary"OnClick ={this.tab}> Display component {oneShowFlag? 2:1}</Button> {oneShowFlag? <FourteenChildOne></FourteenChildOne>:<FourteenChildTwo></FourteenChildTwo>} </div>); }}Copy the code

If it is a single component, it can be short-circuited

oneShowFlag&&<FourteenChildOne></FourteenChildOne>
Copy the code

15. Recursive components

Scenario: The tree component wraps loops using React.Fragment or div

class Item extends React.Component {
  render() {
    const list = this.props.children || [];
    return (
      <div className="item">
        {list.map((item, index) => {
          return(<React.Fragment key={index}> <h3>{item.name}</h3> {// (< item >{item. Children}</ item >) : null} </React.Fragment>); })} </div> ); }}Copy the code

16. Controlled and uncontrolled components

Controlled component: The component’s state is controlled by the React state value state or props

class Controll extends React.Component {
  constructor() {
    super();
    this.state = { value: "This is the controlled component default." };
  }
  render() {
    return<div>{this.state.value}</div>; }}Copy the code

Uncontrolled components: Components are not controlled by React status values, but by DOM properties or React refs

class NoControll extends React.Component {
  render() {
    return<div>{this.props.value}</div>; }}Copy the code

Import code:

export default class Sixteen extends React.Component {
  componentDidMount() {
    console.log(Ref gets uncontrolled component value as, this.refs["noControll"]);
  }
  render() {
    return (
      <div>
        <Controll></Controll>
        <NoControll
          value={"This is an uncontrolled component incoming value."}
          ref="noControll"></NoControll> </div> ); }}Copy the code

17. Advanced Component (HOC)

17.1 define

1. Is a higher-order function definition that takes a component as an argument or returns a component; 2. Functions: Extract duplicate code, realize component reuse, common scenarios, and page reuse; Conditional rendering, control component rendering logic (rendering hijacking), common scenarios, permission control; Capture/hijack the lifecycle of the component being processed, common scenarios, component rendering performance tracking, logging

17.2 Implementation Methods

1. Property broker

import React,{Component} from 'react';

const Seventeen = WrappedComponent =>
  class extends React.Component {
    render() { const props = { ... this.props, name:"This is a high order component."
      };
      return <WrappedComponent {...props} />;
    }
  };

class WrappedComponent extends React.Component {
  state={
     baseName:'Here's the base component.' 
  }
  render() {
    const {baseName} = this.state
    const {name} = this.props
    return<div> <div> {baseName}</div> <div>export default Seventeen(WrappedComponent)
Copy the code

2. The principle of reverse inheritance is to use super to change the this direction of the reorganization, and then can process some container component values in the component

  const Seventeen = (WrappedComponent)=>{
    return class extends WrappedComponent {
        componentDidMount() {
            this.setState({baseName:'This is the base component name modified by reverse inheritance.'})}render() {return super.render();
        }
    }
}

class WrappedComponent extends React.Component {
  state={
     baseName:'Here's the base component.' 
  }
  render() {
    const {baseName} = this.state
    return{baseName}</div> </div>}}export default Seventeen(WrappedComponent);
Copy the code

18. Whether the element is displayed

In general, ternary expressions are used

flag? <div> Display content </div>' 'Flag &&<div> Display content </div>Copy the code

19.Dialog component creation

Dialog is a common component. There are three different ways to create a Dialog

 class NineteenChildOne extends React.Component {
  render() {const Dialog = () => <div> this is shell layer 1</div>;returnthis.props.dialogOneFlag && <Dialog />; }}Copy the code

Method 2: through ReactDom. Render to create outer layer – mount the root node Through the primary the createElement method, the appendChild, RemoveChild and react ReactDOM. Render, ReactDOM unmountComponentAtNode to control elements of the show and hide

NineteenChild.jsx

import ReactDOM from "react-dom";

class Dialog {
  constructor(name) {
    this.div = document.createElement("div");
    this.div.style.width = "200px";
    this.div.style.height = "200px";
    this.div.style.backgroundColor = "green";
    this.div.style.position = "absolute";
    this.div.style.top = "200px";
    this.div.style.left = "400px";
    this.div.id = "dialog-box"; } show(children) {// Destroy const dom = document.querySelector();"#dialog-box");
    if(! Dom) {/ / compatible. Click the / / display the document body. The appendChild (enclosing div); ReactDOM.render(children, this.div); }}destroy() {// Destroy const dom = document.querySelector();"#dialog-box");
    if(dom) {/ / compatible. Click the ReactDOM unmountComponentAtNode (enclosing div); dom.parentNode.removeChild(dom); }}}export default {
  show: function(children) {
    new Dialog().show(children);
  },
  hide: function() { new Dialog().destroy(); }};Copy the code

nineteen.jsx

twoSubmit=()=>{
    Dialog.show("This is shell layer 2.")
  }

  twoCancel=()=>{
    Dialog.hide()
  }
Copy the code

20.React.memo

Function: You can use pureComponent or shouldComponentUpdate to avoid rendering a component when its input properties are the same. Now, you can do the same by wrapping function components in react.memo

import React from "react";

functionAreEqual (prevProps, nextProps) {/* Return if passing nextProps to render returns the same result as passing prevProps to rendertrueOtherwise returnfalse* /if (prevProps.val === nextProps.val) {
    return true;
  } else {
    return false; }} // React.memo() takes two arguments. The first is a pure function and the second is a comparison functionexport default React.memo(function twentyChild(props) {
  console.log("MemoSon rendered : " + Date.now());
  return <div>{props.val}</div>;
}, areEqual);
Copy the code

21.React.PureComponent

React.purecomponent defines a component class like react.purecomponent. 2. The difference is that React.Com Component does not implement shouldComponentUpdate(), whereas React.pureComponent does implement props and state using a shallow comparison. 3.React.PureComponent is used in classes, and React. Memo is used in functions. 4. If the component’s props and state are the same, and the render content is the same, then React.PureComponent can be used to improve performance

Class TwentyOneChild extends React.pureComponent {// Component extends React.pureComponentrender() {
    return <div>{this.props.name}</div>
  }
}

export default class TwentyOne extends React.Component{
    render() {return (
            <div>
              <TwentyOneChild name={'Here's how to use the React.PureComponent'}></TwentyOneChild>
            </div>
        )
    }
}
Copy the code

22.React.Component

React.component.react.component.react.component.react.component.react.component.react.component.react.component.react.component.react.component.react.component.react.component.react.component.react.component.react.component

exportDefault class TwentyTwo extends React.Com {// A component defines a methodrender() {return<div> this is tip 22</div>)Copy the code

23. Print falsy value in JSX

Definition: 1. A falsy value (virtual) is a value that is assumed to be false in a Boolean context; 2. The value is 0, “”,” ‘, ` `, null, and undefined, NaN

export default class TwentyThree extends React.Component{
    state={myVariable:null}
    render() {return (
            <div>{String(this.state.myVariable)}</div>
        )
    }
}
Copy the code

Virtual values, if displayed directly, are implicitly converted to false, so the page is not displayed

24.ReactDOM.createPortal

What it does: Elements returned by a component’s render function are mounted on its parent component, and createPortal provides an excellent way to render child nodes to DOM nodes that exist outside of the parent component

import React from "react";
import ReactDOM from "react-dom";
import {Button} from "antd"

const modalRoot = document.body;

class Modal extends React.Component {
  constructor(props) {
    super(props);
    this.el = document.createElement("div");
    this.el.style.width = "200px";
    this.el.style.height = "200px";
    this.el.style.backgroundColor = "green";
    this.el.style.position = "absolute";
    this.el.style.top = "200px";
    this.el.style.left = "400px";
  }

  componentDidMount() {
    modalRoot.appendChild(this.el);
  }

  componentWillUnmount() {
    modalRoot.removeChild(this.el);
  }

  render() {
    returnReactDOM.createPortal(this.props.children, this.el); }}function Child() {
  return (
    <div className="modal"> reactdom.createPortal </div>); }export default class TwentyFour extends React.Component {
  constructor(props) {
    super(props);
    this.state = { clicks: 0 };
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState(prevState => ({
      clicks: prevState.clicks + 1
    }));
  }

  render() {
    return(<div> <Button onClick={this.handleclick}> {this.state.clicks}</p> <Modal> <Child /> </Modal> </div> ); }}Copy the code

The element is appended to the specified element

25. Use innerHTML in React

Scenario: Some background return HTML fields, so you need to use the innerHTML attribute

export default class TwentyFive extends React.Component {
  render() {
    return (
      <div dangerouslySetInnerHTML={{ __html: " This is the rendered HTML content "}}></div> ); }}Copy the code

26.React.createElement

CreateElement (type, [props], […children])

Source:

export default class TwentySix extends React.Component {
  render() {
    return (
      <div>
        {React.createElement(
          "div",
          { id: "one", className: "two" },
          React.createElement("span", { id: "spanOne" }, "This is the first span tag."),
          React.createElement("br"),
          React.createElement("span", { id: "spanTwo" }, "This is the second span tag.") )} </div> ); }}Copy the code

How it works: Essentially, JSX’s DOM is converted to JS by react.createElement

// JSX syntax <div id='one' class='two'>
    <span id="spanOne">this is spanOne</span>
    <span id="spanTwo"> < span style = "box-sizing: border-box; color: RGB (74, 74, 74); line-height: 22px; font-size: 13px! Important; white-space: inherit! Important;""div",
 { id: "one", class: "two" },
 React.createElement( "span", { id: "spanOne" }, "this is spanOne"), 
 React.createElement("span", { id: "spanTwo" }, "this is spanTwo"));Copy the code

27.React.cloneElement

Grammar:

React.cloneElement(
  element,
  [props],
  [...children]
)
Copy the code

Function: The function of this method is to copy the component, pass values to the component, or add core code for properties

React.Children.map(children, child => {
  return React.cloneElement(child, {
    count: _this.state.count
  });
});
Copy the code

28.React.Fragment

What it does :React.Fragment allows you to aggregate a list of child elements without adding additional nodes to the DOM

render() {
    const { info } = this.state;
    return (
      <div>
        {info.map((item, index) => {
          return (
            <React.Fragment key={index}>
              <div>{item.name}</div>
              <div>{item.age}</div>
            </React.Fragment>
          );
        })}
      </div>
    );
  }
Copy the code

29. Loop elements

There is no internal encapsulation like vue in the V-for instructions, but through the map traversal

{arr.map((item,index)=>{
  return(
    <div key={item.id}>
      <span>{item.name}</span>
      <span>{item.age}</span>
    </div>
  )
})}
Copy the code

Set and get custom properties for the DOM

Function: Some values are passed through custom properties

export default class Thirty extends React.Component {
  click = e => {
    console.log(e.target.getAttribute("data-row"));
  };

  render() {
    return (
      <div>
        <div data-row={"Attribute 1"} data-col={"Property 2"} onClick={this.click}> < div> < div>); }}Copy the code

31. Bind events

Scenarios: An interaction that involves an event click and then clicking the selected value to pass a parameter is also a common scenario

import React from "react";
import { Button } from 'antd'

export default class Three extends React.Component {
  state = {
    flag: true,
    flagOne: 1
  };
  click(data1,data2){
    console.log('data1 value is',data1)
    console.log('data2 value is',data2)
  }
  render() {
    return (
      <div>
        <Button type="primary" onClick={this.click.bind(this,Parameters' 1 '.Parameters' 2 ')}> Click the event </Button> </div>); }}Copy the code

The usage method is detailed in the source routes.js

32.React-Router

32.1 Differences between V3 and V4

1. The earlier version of V3 or V separated the Router and layout components. 2.V4 is a centralized router, through the Route nesting,Layout and page nesting,Layout and page components are part of the router; 3. The routing rule in V3 is EXCLUSIVE, which means that only one route is obtained. 4. Routes in V4 default to inclusive, which means multiple; Can match and render at the same time. If you want to match only one route, you can use “Switch” to render only one route. You can also add “exact” to each route to match “Redirect” or “browser redirection”. If all routes do not match, you can match “Switch”

32.2 the use of

import { HashRouter as Router, Switch  } from "react-router-dom";

class App extends React.Component{
    render(){
        const authPath = '/login'// By default, the page returned when you are not logged in can be set by yourselflet authed = this.props.state.authed || localStorage.getItem('authed') // If you log in, you can use redux to change the valuereturn (
            <Router>
                <Switch>
                    {renderRoutes(routes, authed, authPath)}
                </Switch>
            </Router>
        )
    }
}
Copy the code

V4 is through the Route nesting, realize Layout and page nesting,Switch Switch Route function

33. Style introduction methods

Method 1:import Import

import './App.css';
Copy the code

Mode 2: Inline mode

import React from 'react';

const Header = () => {

    const heading = 'Header component'

    return(
        <div style={{backgroundColor:'orange'<h1>{heading}</h1> </div>)'react';

const footerStyle = {
    width: '100%',
    backgroundColor: 'green',
    padding: '50px',
    font: '30px',
    color: 'white',
    fontWeight: 'bold'
}

export const Footer = () => {
    return(<div style={footerStyle}> </div>)}Copy the code

34. Dynamically bind className

How it works: Control className values through ternary expressions

render(){
  const flag=true
  return (
    <div className={flag?"active":"no-active"< div style = "text-align: center;Copy the code

conclusion

These are the React 34 tips from actual project development; Source address, please stamp welcome star