Detailed explanation of component definition and usage in React
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') )
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') )
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') )
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') )
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') )
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'));
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'));
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
import React from 'react'
import ReactDOM from 'react-dom'
let Component1 = () => {
return <h1>React Component</h1>
}
ReactDOM.render(
<Component1 />,
document.getElementById('app')
)
Copy after loginCopy after login
Class components-ES5 syntaximport React from 'react' import ReactDOM from 'react-dom' let Component1 = () => { return <h1>React Component</h1> } ReactDOM.render( <Component1 />, document.getElementById('app') )
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 loginCopy after login
Class component - ES6 syntaxvar 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') )
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 loginCopy after login
Effect previewComponent summary
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') )
- 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
this.props
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 loginCopy after login
Class componentimport 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') )
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 loginCopy after login
DefaultPropsIn 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. 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') )
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'));
属性的类型规则(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'));
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



CrystalDiskMark is a small HDD benchmark tool for hard drives that quickly measures sequential and random read/write speeds. Next, let the editor introduce CrystalDiskMark to you and how to use crystaldiskmark~ 1. Introduction to CrystalDiskMark CrystalDiskMark is a widely used disk performance testing tool used to evaluate the read and write speed and performance of mechanical hard drives and solid-state drives (SSD). Random I/O performance. It is a free Windows application and provides a user-friendly interface and various test modes to evaluate different aspects of hard drive performance and is widely used in hardware reviews

foobar2000 is a software that can listen to music resources at any time. It brings you all kinds of music with lossless sound quality. The enhanced version of the music player allows you to get a more comprehensive and comfortable music experience. Its design concept is to play the advanced audio on the computer The device is transplanted to mobile phones to provide a more convenient and efficient music playback experience. The interface design is simple, clear and easy to use. It adopts a minimalist design style without too many decorations and cumbersome operations to get started quickly. It also supports a variety of skins and Theme, personalize settings according to your own preferences, and create an exclusive music player that supports the playback of multiple audio formats. It also supports the audio gain function to adjust the volume according to your own hearing conditions to avoid hearing damage caused by excessive volume. Next, let me help you

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

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.

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

Apple rolled out the iOS 17.4 update on Tuesday, bringing a slew of new features and fixes to iPhones. The update includes new emojis, and EU users will also be able to download them from other app stores. In addition, the update also strengthens the control of iPhone security and introduces more "Stolen Device Protection" setting options to provide users with more choices and protection. "iOS17.3 introduces the "Stolen Device Protection" function for the first time, adding extra security to users' sensitive information. When the user is away from home and other familiar places, this function requires the user to enter biometric information for the first time, and after one hour You must enter information again to access and change certain data, such as changing your Apple ID password or turning off stolen device protection.

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

Chirp Down can also be called JJDown. This is a video download tool specially created for Bilibili. However, many friends do not understand this software. Today, let the editor explain to you what Chirp Down is? How to use chirp down. 1. The origin of Chirpdown Chirpdown originated in 2014. It is a very old video downloading software. The interface adopts Win10 tile style, which is simple, beautiful and easy to operate. Chirna is the poster girl of Chirpdown, and the artist is あさひクロイ. Jijidown has always been committed to providing users with the best download experience, constantly updating and optimizing the software, solving various problems and bugs, and adding new functions and features. The function of Chirp Down Chirp Down is
