Props, State and render functions in React

Posted by lukelee on Sun, 12 Apr 2020 19:29:20 +0200

Summary of core features of React

1. React: Declarative Development

(JS or jQuery attribute command development)

2. Can coexist with other frameworks

3. Componentization

4. One-way data flow

(A parent component can directly change the data of a child component, but a child component cannot directly change the data of a parent component)

 

Props, State and render functions

When does the render function execute:

1. When a component is first created, it is executed once

2. When the state data changes, it will be executed again

3. When props data changes, it will be executed again

src/Counter.js

import React,{Component,Fragment} from 'react';

class Counter extends Component{
    constructor(props){
        super(props);
        this.addCount=this.addCount.bind(this);

        this.state={
            counter:1
        }
    }

    addCount(){
        this.setState({
            counter:this.state.counter+1
        })
    }

    render(){
        return(
            <Fragment>
                <button onClick={this.addCount}>click</button>
                <div>{this.state.counter}</div>
            </Fragment>
        )
    }
}

export default Counter;

 

Parent-Child Component Writing

New subcomponent Child.js

import React,{Component,Fragment} from 'react';

class Child extends Component{
    render(){
        return(
            <Fragment>
                <div>{this.props.num}</div>
            </Fragment>
        )
    }
}

export default Child;

Modify parent component Counter.js

import React,{Component,Fragment} from 'react';
import Child from './Child';

class Counter extends Component{
    constructor(props){
        super(props);
        this.addCount=this.addCount.bind(this);

        this.state={
            counter:1
        }
    }

    addCount(){
        this.setState({
            counter:this.state.counter+1
        })
    }

    render(){
        return(
            <Fragment>
                <button onClick={this.addCount}>click</button>
                <Child num={this.state.counter}/>
            </Fragment>
        )
    }
}

export default Counter;

The result is the same as before

Topics: Javascript Fragment React JQuery Attribute