Table of Contents
Components
Simple implementation of components - functional components
Class components-ES5 syntax
Class component - ES6 syntax
Component summary
Component properties (Props)
function Component
Class component
DefaultProps
Attribute type rules (propTypes)
属性的类型规则(propTypes)
Home Web Front-end JS Tutorial Detailed explanation of component definition and usage in React

Detailed explanation of component definition and usage in React

May 24, 2018 pm 02:39 PM
react use Detailed explanation

This time I will bring you a detailed explanation of the use of component definitions in React. What are the precautions for the use of component definitions in React. The following is a practical case, let's take a look.

Components

Components allow you to divide the UI into independent, reusable widgets, and design each widget individually.

Plays an important role in single page applications (SPA)

Simple implementation of components - functional components

import React from 'react'
import ReactDOM from 'react-dom'
let Component1 = () => {
    return <h1>React Component</h1>
}
ReactDOM.render(
    <Component1 />,
    document.getElementById('app')
)
Copy after login
Copy after login

Class components-ES5 syntax

var React = require('react');
var ReactDOM = require('react-dom')
var Component1 = React.createClass({
    render: function(){
        return (
            <p>
                <h1>Tom</h1>
                <h1>Sam</h1>
            </p>
        )
    }
})
ReactDOM.render(
    <Component1 />,
    document.getElementById('app')
)
Copy after login
Copy after login

Class component - ES6 syntax

import React from 'react'
import ReactDOM from 'react-dom'
class Component1 extends React.Component{
    render(){
        return (
            <p>
                <h1>Tom</h1>
                <h1>Sam</h1>
            </p>
        ) 
    }
}
ReactDOM.render(
    <Component1 />,
    document.getElementById('app')
)
Copy after login
Copy after login

Effect preview

Component summary

  • The first letter of the component name must be capitalized

  • The function returns a virtual DOM node

  • Class components must have a render method

  • render must return a virtual DOM node

  • In actual work, class components are a commonly used method

Component properties (Props)

Because the call of the component is In the form of html tags, and html tags can add attributes, so custom attributes can also be added to React components, and the attributes are obtained using the this.props

function Component

import React from 'react'
import ReactDOM from 'react-dom'
let Component1 = (props) => {
    return <h1>name-{props.name}</h1>
}
ReactDOM.render(
    <Component1 name="Sam"/>,
    document.getElementById('app')
)
Copy after login
Copy after login

Class component

import React from 'react'
import ReactDOM from 'react-dom'
class Component1 extends React.Component{
    render(){
        return <h1>name-{this.props.name}</h1> 
    }
}
ReactDOM.render(
    <Component1 name="Sam"/>,
    document.getElementById('app')
)
Copy after login
Copy after login

DefaultProps

In addition to passing values ​​in the form of DOM node attributes when calling, the properties of components can also be set to default If the corresponding attribute value is not passed when calling, the default attribute value will be used.
getDefalutProps This method will only be called once.

//es5
var React = require('react');
var ReactDOM = require('react-dom');
var Component1 = React.createClass({
    getDefaultProps: function(){
        return {
            name: 'Tom',
            age: 20
        }
    },
    render: function(){
        return (
            <p>
                <p>姓名:{this.props.name}</p>
                <p>年龄:{this.props.age}</p>
            </p>
        )            
    }    
})
//es6
import React from 'react';
import ReactDOM from 'react-dom';
class Component1 extends React.Component{
    static defaultProps = {
        name: 'Tom',
        age: 20
    }
    render(){
        return (
            <p>
                <h1>姓名:{this.props.name}</h1>
                <h1>年龄:{this.props.age}</h1>
            </p>
        )
    }
}
//或者
Component1.defaultProps = {
    name: "Sam",
    age: 22
}
//使用
ReactDOM.render(<Component1/>, document.getElementById('p1'));
Copy after login
Copy after login

Attribute type rules (propTypes)

Normally, when defining a component, the attributes are defined and some usage conditions are added, such as certain attribute values. Data type must be an array, or some properties cannot be empty. At this time, they can be set through propTypes.

import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types'
class Component1 extends React.Component{
    render(){
        return (
            <p>
                <p>姓名:{this.props.name}</p>
                <p>年龄:{this.props.age}</p>
                <p>学科:</p>
                <ul>
                {
                    this.props.subjects.map(function(_item){
                        return <li>{_item}</li>
                    })
                }
                </ul>
            </p>
        )
    }
}
//定义属性 name 为字符串且必须有值
Component1.propTypes = {
    name: PropTypes.string
}
ReactDOM.render(<Component1 name="Tom"/>, document.getElementById('p1'));
Copy after login
Copy after login

prop is optional by default, commonly used types:

  • PropTypes.array

  • PropTypes.bool

  • PropTypes.func

  • PropTypes.number

  • PropTypes.object

  • ##PropTypes.string

  • PropTypes.symbol

  • PropTypes.any.isRequired

Component

Components allow you to divide the UI into independent, reusable widgets, and design each widget individually.

Plays an important role in single page applications (SPA)

Simple implementation of components - functional components

import React from 'react'
import ReactDOM from 'react-dom'
let Component1 = () => {
    return <h1>React Component</h1>
}
ReactDOM.render(
    <Component1 />,
    document.getElementById('app')
)
Copy after login
Copy after login

Class components-ES5 syntax

var React = require('react');
var ReactDOM = require('react-dom')
var Component1 = React.createClass({
    render: function(){
        return (
            <p>
                <h1>Tom</h1>
                <h1>Sam</h1>
            </p>
        )
    }
})
ReactDOM.render(
    <Component1 />,
    document.getElementById('app')
)
Copy after login
Copy after login

Class component - ES6 syntax

import React from 'react'
import ReactDOM from 'react-dom'
class Component1 extends React.Component{
    render(){
        return (
            <p>
                <h1>Tom</h1>
                <h1>Sam</h1>
            </p>
        ) 
    }
}
ReactDOM.render(
    <Component1 />,
    document.getElementById('app')
)
Copy after login
Copy after login

Effect preview

Component summary

  • The first letter of the component name must be capitalized

  • The function returns a virtual DOM node

  • Class components must have a render method

  • render must return a virtual DOM node

  • In actual work, class components are a commonly used method

Component properties (Props)

Because the call of the component is In the form of html tags, and html tags can add attributes, so custom attributes can also be added to React components, and the attributes are obtained using the

this.props

function Component

import React from 'react'
import ReactDOM from 'react-dom'
let Component1 = (props) => {
    return <h1>name-{props.name}</h1>
}
ReactDOM.render(
    <Component1 name="Sam"/>,
    document.getElementById('app')
)
Copy after login
Copy after login

Class component

import React from 'react'
import ReactDOM from 'react-dom'
class Component1 extends React.Component{
    render(){
        return <h1>name-{this.props.name}</h1> 
    }
}
ReactDOM.render(
    <Component1 name="Sam"/>,
    document.getElementById('app')
)
Copy after login
Copy after login

DefaultProps

In addition to passing values ​​in the form of DOM node attributes when calling, the properties of components can also be set to default If the corresponding attribute value is not passed when calling, the default attribute value will be used.


getDefalutProps This method will only be called once.

//es5
var React = require('react');
var ReactDOM = require('react-dom');
var Component1 = React.createClass({
    getDefaultProps: function(){
        return {
            name: 'Tom',
            age: 20
        }
    },
    render: function(){
        return (
            <p>
                <p>姓名:{this.props.name}</p>
                <p>年龄:{this.props.age}</p>
            </p>
        )            
    }    
})
//es6
import React from 'react';
import ReactDOM from 'react-dom';
class Component1 extends React.Component{
    static defaultProps = {
        name: 'Tom',
        age: 20
    }
    render(){
        return (
            <p>
                <h1>姓名:{this.props.name}</h1>
                <h1>年龄:{this.props.age}</h1>
            </p>
        )
    }
}
//或者
Component1.defaultProps = {
    name: "Sam",
    age: 22
}
//使用
ReactDOM.render(<Component1/>, document.getElementById('p1'));
Copy after login
Copy after login

属性的类型规则(propTypes)

通常情况下,在定义一个组件的时候把属性定义好,会加上一些使用的条件限制,比如某些属性值的数据类型必须是数组,或者某些属性不能为空,在这个时候,可以通过 propTypes 来设置。

import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types'
class Component1 extends React.Component{
    render(){
        return (
            <p>
                <p>姓名:{this.props.name}</p>
                <p>年龄:{this.props.age}</p>
                <p>学科:</p>
                <ul>
                {
                    this.props.subjects.map(function(_item){
                        return <li>{_item}</li>
                    })
                }
                </ul>
            </p>
        )
    }
}
//定义属性 name 为字符串且必须有值
Component1.propTypes = {
    name: PropTypes.string
}
ReactDOM.render(<Component1 name="Tom"/>, document.getElementById('p1'));
Copy after login
Copy after login

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

react实现选中li高亮步骤详解

前端中排序算法实例详解

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

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? Apr 26, 2024 am 09:40 AM

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

How to use NetEase Mailbox Master How to use NetEase Mailbox Master Mar 27, 2024 pm 05:32 PM

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

How to use Baidu Netdisk app How to use Baidu Netdisk app Mar 27, 2024 pm 06:46 PM

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

How to use Xiaomi Auto app How to use Xiaomi Auto app Apr 01, 2024 pm 09:19 PM

Xiaomi car software provides remote car control functions, allowing users to remotely control the vehicle through mobile phones or computers, such as opening and closing the vehicle's doors and windows, starting the engine, controlling the vehicle's air conditioner and audio, etc. The following is the use and content of this software, let's learn about it together . Comprehensive list of Xiaomi Auto app functions and usage methods 1. The Xiaomi Auto app was launched on the Apple AppStore on March 25, and can now be downloaded from the app store on Android phones; Car purchase: Learn about the core highlights and technical parameters of Xiaomi Auto, and make an appointment for a test drive. Configure and order your Xiaomi car, and support online processing of car pickup to-do items. 3. Community: Understand Xiaomi Auto brand information, exchange car experience, and share wonderful car life; 4. Car control: The mobile phone is the remote control, remote control, real-time security, easy

How to use spaces correctly in Go How to use spaces correctly in Go Mar 29, 2024 pm 03:42 PM

Go language is a simple, efficient, and highly concurrency programming language. It is an open source language developed by Google. In the Go language, the use of spaces is very important, it can improve the readability and maintainability of the code. This article will introduce how to use spaces correctly in Go language and provide specific code examples. Why you need to use spaces correctly In the programming process, the use of spaces is very important for the readability and beauty of the code. Appropriate use of spaces can make code clearer and easier to read, thus reducing

Integration of Java framework and front-end React framework Integration of Java framework and front-end React framework Jun 01, 2024 pm 03:16 PM

Integration of Java framework and React framework: Steps: Set up the back-end Java framework. Create project structure. Configure build tools. Create React applications. Write REST API endpoints. Configure the communication mechanism. Practical case (SpringBoot+React): Java code: Define RESTfulAPI controller. React code: Get and display the data returned by the API.

The definition and use of full-width characters The definition and use of full-width characters Mar 25, 2024 pm 03:33 PM

What are full-width characters? In computer encoding systems, double-width characters are a character encoding method that takes up two standard character positions. Correspondingly, the character encoding method that occupies a standard character position is called a half-width character. Full-width characters are usually used for input, display and printing of Chinese, Japanese, Korean and other Asian characters. In Chinese input methods and text editing, the usage scenarios of full-width characters and half-width characters are different. Use of full-width characters Chinese input method: In the Chinese input method, full-width characters are usually used to input Chinese characters, such as Chinese characters, symbols, etc.

How to use Dewu installment purchase How to use Dewu installment purchase Mar 24, 2024 pm 01:46 PM

How to use Dewu installment purchase? You can use the installment payment service to purchase your favorite goods in Dewu APP. Most people don’t know how to use Dewu installment purchase. Next is the Dewu installment purchase brought by the editor to users. Graphic tutorial on how to use it. Interested users can come and take a look! Dewu usage tutorial How to use Dewu installment purchase 1. First open Dewu APP and enter the main page, select your favorite product and enter the purchase page; 2. Then on the product purchase page in the picture below, click [Buy Now] in the lower right corner; 3 , then select the appropriate code number and click the price on the left; 4. Then on the order confirmation page, select [Submit Order] in the lower right corner; 5. Finally, on the payment page, check the button behind [Huabei Installment]. Just select the installment type and you’re done

See all articles