React.ponent class components


1. Create a component

(SRC — > Components — > component.js)

import React from 'react';
class Text extends React.Component{
    constructor(){
        super(a); } render(){// One way to write a style
        let obj={
            color:'red'
        }
        return <div style={obj}>
            hello word~
        </div>
    }
}
export default Text;
Copy the code

2) Introduce it in app.js

import React from 'react';
import './App.css';

import Text from './components/Shiyan.js'
function App(a) {
  return (
    <div className="App">
      <Text></Text>
    </div>
  );
}

export default App;
Copy the code

2. Obtain the value of the input box

import React from 'react';

class Xxxx extends React.Component{
    render() {
        return (
            <div>
                <input type="text" ref={(input)= >{this.text = input}}/>
                <button onClick={() = >{console.log(this.text.value)}}> dot</button>
            </div>)}}export default Xxxx;
Copy the code

3. Change the view with data

Control div display hidden

import React,{Component} from 'react';
Yong ES6 builds a class that inherits the following components
export default class Images extends Component {
    constructor(props){
        super(props);
        this.state={
            stage:0
        }
    }
    render() {
        // Get the value from the state structure
        let {stage} = this.state;
        return (
            <div>            
                {/* control, display hidden 0 when displayed, non-zero when hidden */} {/* Put the expression on the outside and the style */ on the inside}
                <div style={{
                    display:stage===0?'block':'none',background:'red'
                }}>
                </div>
            </div>
        )
    }
}

Copy the code

Second, the use of

1, the operation of style

1) Dynamically add a class name

import React, { Component } from 'react'
export default class one extends Component {
    render() {
        // Add the class name according to the variable
        let isActive = true;
        return (
            <div>{/*};} {/*};<p className={`boxThe ${isActive? 'zhen':'jiade'} `} >eeeeee</p>
            </div>)}}Copy the code

2) Inline style

import React, { Component } from 'react'
export default class one extends Component {
    render() {
        return (
            <div>{/* Since it is a js file, the styles are set in quotes and separated by commas; Add two layers of parentheses. The first layer is for parsing and the second layer is for writing styles.<div style={{width:'100px',height:'100px',background:'red'}} ></div>
            </div>)}}Copy the code

2. Conditional judgment

1) The ternary operator

import React, { Component } from 'react'
export default class List extends Component {
    render() {
        // The tag is an object
        const redBox = <div style={{width:'50px',height:'50px',background:'red'}}></div>
        const blueBox = <div style={{width:'50px',height:'50px',background:'blue'}}></div>
        const yellowBox = <div style={{width:'50px',height:'50px',background:'yellow'}}></div>

        // There is a variable below
        let value = 'yellow';
        return (
            <div>
                {
                    // If value is equal to yellow, then the red box is displayed
                   value==='red'? redBox:(
                        // This shows the yellow box
                       value==='blue'? blueBox:yellowBox ) } </div> ) } }Copy the code

2) the ampersand operator () is used to run the ampersand operator ()

import React, { Component } from 'react'
export default class List extends Component {
    render() {
        let show=true;
        return (
            <div>{// when show is true, the following div show && is displayed<div style={{width:'100px',height:'100px',background:'#999'}} ></div>
                }
            </div>)}}Copy the code

Note: 3) | | or operator when current is really does not display, display is false

import React, { Component } from 'react'
export default class List extends Component {
    render() {
        let shows=false;
        return (
            <div>
                {
                    shows || <div style={{width:'100px',height:'100px',background:'green'}} ></div>
                }
            </div>)}}Copy the code

3, convenient

Note: All the conveniences are based on the map method, except for running the function itself, which returns a new array.

1) Convenient objects

① The first way to write

import React, { Component } from 'react'
export default class List extends Component {

    render(){
        let obj={
            a:1.b:2.c:3
        }
        return (
            <div>{/ * object traversal method * /} {/ / write a since the operation function (here () = > {let dom = []; for(const key in obj){ if(obj.hasOwnProperty(key)){ const value=obj[key]; // Insert the above into the dom dom.push(<p key={key}>Key: {key}; Value: {value}</p>} // return dom; // return dom; }}) ()</div>)}}Copy the code

② The second way to write

import React, { Component } from 'react'
export default class List extends Component {

    render(){
        let obj={
            a:1.b:2.c:3
        }
        return (
            <div>{/* object.entries (where you put Object names), he takes the keys and values of objects, and each entry is an array; The first one in the array is the key, the second one is the value; [[key,value], [key,value]] */} {// And the item is a small array, Entries (obj).map(([key,value],index)=>{return<p key={key}>Key: {key} -- -- -- the value: {value}</p>}) object.entries (obj).map(([key,value],index)=><p key={key}>{value}</p>
                }
            </div>)}}Copy the code

2) Convenience strings

import React, { Component } from 'react'
export default class List extends Component {

    render(){
        let str = 'hello'
        return (
            <div>
                {
                    str.split('').map((item,index)=>(
                        <p key={index}>{item}</p>))}</div>)}}Copy the code

3) Convenience numbers

import React, { Component } from 'react'
export default class List extends Component {
    render(){
        let num = 5;// From convenience to convenience
        return (
            <div>New Array(num).fill(" ").map((item,index)=>(<p key={index}>{index + 1}</p>))}</div>)}}Copy the code

4. Add the list

1) Normal child component pass value

(1) Add in component A

import React, { Component } from 'react'
export class Add extends Component {
    constructor() {
        super(a);this.state = {
            value: ""
        };
    }
    render() {
        return (
            <div>
                <input
                    type="text"
                    value={this.state.value}
                    onChange={this.textChangeAction}
                />
                <button onClick={this.btnAction}>new</button>
            </div>
        )
    }
    textChangeAction= ev= >{
        this.setState({
            value:ev.target.value
        })
    }
    btnAction=() = >{
        // This section passes the value to the husband, and the husband passes it to another child. This is called state promotion
        const value = this.state.value;
        // Pass the value to the onAdd function of the var component, calling the function with props
        this.props.onAdd(value);
        // This is received. I am emptying the input field
        this.setState({
            value:' '}}})export default Add;

Copy the code

(2) Receive in the parent component, leaving a child component in the pass

import React, { Component } from 'react'
import Add from '.. /components/input/Add';
import List from '.. /components/input/List';
export default class Mine extends Component {
    constructor(){
        super(a);this.state={
            // After the zai user has added, save it for him
            dataSource: []}}render() {
        return (
            <div>{/ *<Links />* /}<Add onAdd={this.handleAdd} />{/* this is my son */}<List data={this.state.dataSource} />
                
            </div>
        )
    }
    handleAdd=(value) = >{
        console.log('I received the value for the new component :',value);
        this.setState({
            dataSource: [
                ...this.state.dataSource,
                {
                    id: new Date().getTime(),
                    value
                }
            ]
        })
    }
}

Copy the code

③ Display in component B

import React, { Component } from 'react'

export class List extends Component {
    render() {
        return (
            <div>
                <h1>The list of</h1>{/ * this convenient to receive * /} {/ / {id, value} this originally is a item this. Props. The data. The map (({id, value}) = > (<p key={id}> {value} </p>))}</div>)}}export default List;
Copy the code

2) Non-parent component pass values

Note: Component A passes directly to component B

① Use EventBus in vUE

Note: Public — >index. HTML

export default new window.Vue();
Copy the code

C. Import and send data in component A

import React, { Component } from 'react'
/ / to introduce him
import EventBus from '.. /.. /EventBus';
export class Add extends Component {
    constructor() {
        super(a);this.state = {
            value: ""
        };
    }
    render() {
        return (
            <div>
                <input
                    type="text"
                    value={this.state.value}
                    onChange={this.textChangeAction}
                />
                <button onClick={this.btnAction}>new</button>
            </div>
        )
    }
    textChangeAction= ev= >{
        this.setState({
            value:ev.target.value
        })
    }
    btnAction=() = >{
        // This section passes the value to the husband, and the husband passes it to another child. This is called state promotion
        const value = this.state.value;
        // Fires the function, passing in arguments
        EventBus.$emit('add',value)
        // Empty the input box
        this.setState({
            value:' '}}})export default Add;
Copy the code

D, receive in component B

import React, { Component } from 'react'
import EventBus from '.. /.. /EventBus';
export class List extends Component {
    constructor(){
        super(a);this.state={
            data: []}}render() {
        return (
            <div>
                <h1>The list of</h1>{/ * this convenient to receive * /} {/ / {id, value} this originally is a item. This state. The data. The map (({id, value}) = > (<p key={id}> {value} </p>))}</div>)}// Monitor this event
    componentDidMount(){
        // Listen for events, shown here
        // The event is triggered
        // EventBus.$on('add',(... rest)=>{
        EventBus.$on('add'.(value) = >{
            // console.log(' triggered: ',rest)
            console.log('Triggered',value);
            this.setState({
                data:[...this.state.data,{
                    id:new Date().getTime(),
                    value
                }]
            })
        })
    }
    componentWillUnmount(){
     	// Before the component is destroyed, remove the tap (to give him a judgment)
     	EventBus.$soff('add'); }}export default List;
Copy the code

E. To introduce the two sibling components in the page

import React, { Component } from 'react'
import Add from '.. /components/Add';
import List from '.. /components/List';
export default class Mine extends Component {
    constructor(){
        super(a);this.state={
         
        }
    }
    
    render() {
        return (
            <div>
                <Add />
                <List />
                
            </div>)}}Copy the code

(2) using pubsub – js

A, install NPM I pubsub-js-s b, use a and B components in the parent page

import React, { Component } from 'react'
import Add from '.. /components/input/Add';
import List from '.. /components/input/List';
export default class Mine extends Component {
    constructor(){
        super(a);this.state={
            show:true}}render() {
        return (
            <div>
                <Add />
                <button onClick={()= >{this.setState({show: ! This.state.show})}}> button (simulate memory leak)</button>{/* control whether the following button is destroyed */} {this.state.show &&<List />}
            </div>)}}Copy the code

C. Send data in component A

import React, { Component } from 'react'
/ / to introduce him
import PubSub from 'pubsub-js';

export class Add extends Component {
    constructor() {
        super(a);this.state = {
            value: ""
        };
    }
    render() {
        return (
            <div>
                <input
                    type="text"
                    value={this.state.value}
                    onChange={this.textChangeAction}
                />
                <button onClick={this.btnAction}>new</button>
            </div>
        )
    }
    textChangeAction= ev= >{
        this.setState({
            value:ev.target.value
        })
    }
    btnAction=() = >{
        const value=this.state.value;
        PubSub.publish('add',value)
            // Empty the input box
            this.setState({
                value:' '}}})export default Add;
Copy the code

D, receive in component B

import React, { Component } from 'react'
/ / introduction
import PubSub from 'pubsub-js';
export class List extends Component {
    constructor(){
        super(a);this.state={
            data: []}}render() {
        return (
            <div>
                <h1>The list of</h1>{/ * this convenient to receive * /} {/ / {id, value} this originally is a item. This state. The data. The map (({id, value}) = > (<p key={id}> {value} </p>))}</div>)}// Monitor this event
    componentDidMount(){
       Pubsub. subscribe('add',(... Rest)=>{console.log(' triggered: ',rest)}) */
        console.log('Listener added');
        // This receives, as above, two values. The first is the event name and the second is the value
        // It will be removed when the component is destroyed, so it will be removed, but it is not a variable for componentWillUnmount, so it will be elevated
        this.xiaoming = PubSub.subscribe('add'.(eventName,value) = >{
            console.log('Triggered:',value);
            this.setState({
                data:[...this.state.data,{
                    id:new Date().getTime(),
                    value
                }]
            })
        })
    }
    componentWillUnmount(){
        console.log('Remove listen');
        // Before the component is destroyed, remove the listener (the zai section gives him a judgment). The reason for removing the listener is because there is a closure on it, and if not destroyed, there will be a memory leak
        PubSub.unsubscribe(this.xiaoming); }}export default List;
Copy the code

5. Add, delete and modify the data in state

Note: You cannot change the state directly, so you do not change the original data

1) Array modification

import React, { Component } from 'react'
class Shengming extends Component {
    constructor(){
        super(a);// Component internal property declarations need to be written in constructor
        this.state={ // Make state immutable
            num: [1.2.3.4.5]}}/ / new
    fun=() = >{
        this.setState({
            // Expand the existing data and add new data
            / / method
            num:[...this.state.num,6]./ / method 2
            num:this.state.num.concat(6)})}/ / delete
    del=() = >{
        this.setState({
            num:this.state.num.filter((item,index) = >index ! = =2)It removes the element whose subscript is 2})}/ / modify
    modify=() = >{
        this.setState({
            // Replace the element with the subscript 2. Replace that with 10
            num:this.state.num.map((item,index) = >(index === 2 ? 10 : item))
        })
    }
    render() {
        return (
            <div>
                <button onClick={this.fun}>add</button>
                <button onClick={this.del}>delete</button>
                <button onClick={this.modify}>Modify the</button>
                <p>{this.state.num}</p>
            </div>)}}export default Shengming;
Copy the code

2) Object modification

import React, { Component } from 'react'

class Shen extends Component {
    constructor(){
        super(a);// Component internal property declarations need to be written in constructor
        this.state={ // Make state immutable
            obj: {a:1.b:3
            }
        }
    }
   modify=() = >{
        // Object modification
        this.setState({
            / / the first
            obj: {
                ...this.state.obj,
                b: 20
            },
            / / the second
            /* object.assign (argument 1, argument 2, argument 3) The first argument is the empty Object. Argument 2 is the value to be merged into the empty Object (the one that was merged first). Argument 3 is the value to be modified
            obj:Object.assign({},this.state.obj,{b:30})})}render() {
        return (
            <div>
                <button onClick={this.modify}>Modify the</button>
                <p>{this.state.obj.b}</p>
            </div>)}}export default Shen;
Copy the code

Iii. Life cycle

ComponentWillMount Called before component rendering

ComponentDidMount Called after component rendering

ComponentWillReceiveProps component props change after the call

ShouldComponentUpdate determines whether a component should update HTML

ComponentWillUpdate Called when the component is about to update HTML

ComponentDidUpdate is called immediately after a component is updated.

ComponentWillUnmount is called immediately before the component is removed from the DOM.

ReactDOM.unmountComponentAtNode(document.getElementById(" ")); // Uninstall components