Home > Web Front-end > JS Tutorial > body text

Detailed explanation of component rendering in React

php中世界最好的语言
Release: 2018-05-24 14:38:23
Original
1726 people have browsed it

This time I will bring you a detailed explanation of the use of component rendering in React. What are the precautions when using component rendering in React. Here are practical cases, let’s take a look.

Component rendering - conditional rendering (dynamic component)

In many cases the component is dynamically rendered, such as login status. If logged in, log out will be displayed, otherwise login will be displayed

import React from 'react'
let Login = (props) => {
    return <input type="button" value="login" onClick={props.click}/>;
}
let Logout = (props) => {
    return <input type="button" value="logout" onClick={props.click}/>;
}
export default class CP extends React.Component{
    state = {
        status: 0
    }
    login(){
        this.setState({status: 1})
    }
    logout(){
        this.setState({status: 0})
    }
    render(){
        let button = null;
        if(this.state.status == 0){
            button = <Login click={this.login.bind(this)}/>
        } else {
            button = <Logout click={this.logout.bind(this)} />
        }
        return <p>{button}</p>
    }
}
Copy after login

Effect preview

Component rendering - list rendering

React has no instructions, so you have to use an array to complete the list rendering.

List rendering——Simple implementation

import React from 'react'
import ReactDOM from 'react-dom'
let Component1 = () => {
    let lis = [<li key="Javascript">Javascript</li>, <li key="Vue">Vue</li>, <li key="React">React</li>]
    return (
        <p>
            <ul>
                {lis}
            </ul>
        </p>
    )
}
ReactDOM.render(
    <Component1 />
    document.getElementById('app')
)
Copy after login

List rendering——Loop for

import React from 'react'
import ReactDOM from 'react-dom'
let Component1 = () => {
    let data = ['Javascript', 'Vue', 'React']
    let lis = [];
    for(let frm of frms){
        lis.push(<li key={frm}>{frm}</li>)
    }
    return (
        <p>
            <ul>
                {lis}
            </ul>
        </p>
    )
}
ReactDOM.render(
    <Component1 />
    document.getElementById('app')
)
Copy after login

List rendering——Loop map

import React from 'react'
import ReactDOM from 'react-dom'
let Component1 = () => {
    let data = ['Javascript', 'Vue', 'React']
    let lis = data.map((frm) => {
        return <li key={frm}>{frm}</li>
    });
    return (
        <p>
            <ul>
                {lis}
            </ul>
        </p>
    )
}
ReactDOM.render(
    <Component1 />
    document.getElementById('app')
)
Copy after login

List rendering——Object Array

import React from 'react'
import ReactDOM from 'react-dom'
class Component1 extends React.Component {
    constructor(props){
        super(props)
    }
    static defaultProps = {
        students: [
            {id: 1, name: 'Tom', age: 18, gender: 1}, 
            {id: 2, name: 'Sam', age: 22, gender: 1}, 
            {id: 3, name: 'Lucy', age: 20, gender: 0}
        ]
    }
    getKeys(item = {}){
        return Object.keys(item)
    }
    render(){
        return (
            <table>
                <thead>
                    <tr>
                        {
                            this.getKeys(this.props.students[0]).map((key) => {
                                return <th key={key}>{key}</th>
                            })
                        }
                    </tr>
                </thead>
                <tbody>
                    {
                        this.props.students.map((obj) => {
                            return (
                                <tr key={obj.id}>
                                    {
                                        this.getKeys(obj).map((key, idx) => {
                                            return <td key={key + idx}>{obj[key]}</td>
                                        })
                                    }
                                </tr>
                            )
                        })
                    }
                </tbody>
            </table>
        )
    }
}
ReactDOM.render(
    <Component1 />,
    document.getElementById('app')
)
Copy after login

List rendering - Keys

Because React is a process from virtual DOM to real DOM, and DOM itself is an object, the object does not have a unique identifier by default, so it needs to be done manually specified.

Keys help React identify which item has been modified, added, or removed. Each element in the array should be identified by a unique and immutable key.

Keys are used in list rendering and must be unique among sibling elements.

Component rendering - component child nodes

Because the component is called as a DOM node, the component can contain child nodes. React obtains the child nodes of the component through this.props.children. Usually this.props.children will have the following situations

  1. If the current component has no child nodes, it is undefined

  2. If there is a child node, The data type is object

  3. If there are multiple child nodes, the data type is array

In order to solve the problem of inconsistent data types that require constant judgment during use, React provides a method Reactth.Children to handle this property.

var Component1 = React.createClass({
    render: function(){
        return (
            <p>                        
                {
                    React.Children.map(this.props.children, function(childNode){
                        return <li>{childNode}</li>
                    })
                }
            </p>
        );
    }
})
ReactDOM.render(
    <Component1>
        <span>Tom</span>
        <span>Sam</span>
    </Component1>, document.getElementById('p1'));
Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Detailed explanation of the sorting algorithm example in the front end

Detailed explanation of the implementation steps of PromiseA

The above is the detailed content of Detailed explanation of component rendering in React. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!