Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The method of creating components in React

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

Today, the editor will share with you the relevant knowledge points about the method of creating components in React. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look.

Component introduction

Components allows you to divide the user interface into separate, reusable widgets, and each part can be designed separately.

By definition, components are like functions of JavaScript. The component can receive any input (called "props") and return a React element to describe what is displayed on the screen.

Props, or Property, is written as props in the code, so props can be used to refer to properties.

There are two kinds of components in react: class component (class components) and function component (function components)

Create a class component

The definition of class components has the following requirements:

Class components need to inherit from React.Component

Class components must implement render functions

Before ES6, class components can be defined through the create-react-class module, but the official website recommends that we use the class class definition of ES6.

Use class to define a component:

Class App extends Component {constructor () {super () this.state = {}} render () {return Hello App}}

Let's analyze in detail the parts of the class component.

Constructor: this is the constructor of the class component, which is optional, and we usually initialize some data in constructor

This.state: we add the state attribute to the class component in constructor. You can understand that there is a state object in the component, which contains various properties to maintain the data within the component. At the same time, you can use this.state. Access this property

Render (): this method is the only method that must be implemented in the class component, and the class component returns the display content of the component through render ().

About state

We can add data objects to class components through this.state, and we can add data objects to class components through this.state. To access the properties in our setState.

Constructor (props) {super (props); this.state = {name: "xhs-rookies"}} render () {return {this.state.name}}

But when we want to modify the name property in the above example, we must add or modify the value to the state through the setState () method specified by react.

This.state.name = 'new xhs-rookies' / / wrong way, this.setState ({name:' new xhs-rookies'}) / / correct way is not allowed

To put it simply, in react, the page is rendered by data, using setState () to update the data, react will help us execute render () to update the page, thus updating all the data used in the state in the page.

About render

When render is called, it checks the changes of this.props and this.state and returns many types. In many cases, we choose to let this method return the React element, and then leave it to React to render the display:

React element:

It is usually created through JSX.

For example, it will be rendered as a DOM node by React and as a custom component by React

Both are React elements.

For more information on the render () method, see React.Component-Render)

Create function components

A function component is a function that is defined using function, but this function returns the same content as the render function in the class component.

Compared with class components, function components have their own characteristics:

No lifecycle, it will also be updated and mounted, but there is no lifecycle function

No this (component instance)

No internal state (state)

Let's define a function component:

Export default function App () {return xhs rookies} rendering component

In previous articles, we only encountered React elements that represent DOM tags:

Const element =

However, elements can also represent user-defined components:

Const element =

When React encounters an element that represents a user-defined component, it passes the JSX attribute to the corresponding component as a separate object. We call it a "props" object.

For example, the following code renders "xhs rookies" on the page:

Function Welcome (props) {return Hello, {props.name}} const element = ReactDOM.render (element, document.getElementById ('root'))

Let's briefly explain the above example:

We called the ReactDOM.render () method and passed elements into it.

React invokes the Welcome component and passes in {name: 'xhs rookies'} as a props object.

The Welcome component returns xhs rookies.

React DOM quickly updates DOM so that it appears as xhs rookies.

Note: component names always start with uppercase letters.

For example, it represents a DOM tag and represents a component, and you need to have a Welcome component in the scope.

You can read more about the reasons behind this in-depth JSX.

Synthetic component

Components can reference other components in their output. This allows us to use the same components to abstract to any level. A button, a form, a dialog box, a screen: in React applications, all of these are usually described as components.

For example, we can create an App component and render Welcome multiple times inside it:

Function Welcome (props) {return Hello, {props.name}} function App () {return ()} ReactDOM.render (, document.getElementById ('root'))

Typically, a new React apps has a separate top-level App component. However, if you integrate React in an existing application, you may need to integrate from bottom to top, starting with widgets like Button, and gradually integrating to the top of the view layer.

Extract component

Don't be afraid to divide a component into smaller components.

For example, consider the following Comment component:

Function Comment (props) {return (

{props.author.name}

{props.author.name} {props.text} {formatDate (props.date)})}

It accepts author (an object), text (a string), and date (a date) as props.

This component is troublesome to modify because it is nested and it is difficult to reuse some of it. Let's extract some components from it.

First, extract the avatar Avatar:

Function Avatar (props) {return

{props.user.name}

}

The Avatar component does not care how it is rendered in Comment. This is why we have a more generic property name for its prop: user, rather than author.

We recommend naming the props from the perspective of the component itself rather than the context in which it is used.

We can simplify Comment components a little bit:

Function Comment (props) {return ({props.author.name} {props.text} {formatDate (props.date)})}

Next, we extract the user information UserInfo component to display the Avatar next to the user name:

Function UserInfo (props) {return ({props.user.name})}

This allows us to further simplify Comment components:

Function Comment (props) {return ({props.text} {formatDate (props.date)})}

Extracting components may seem like a tedious task, but what can be rewarded in a large Apps is a large number of reusable components. A good rule of thumb is that if part of your UI needs to be used multiple times (Button,Panel,Avatar) or is complex enough (App,FeedStory,Comment), the best thing to do is to make it a reusable component.

Props is read-only

Whether you declare a component with a function or class method, it cannot modify its own props. Consider the following sum (summation) functions:

Function sum (a, b) {return a + b}

Such functions are called "pure functions" because they do not try to change their input and always get the same results for the same input.

Conversely, the following is a non-pure function because it changes its own input value:

Function withdraw (account, amount) {account.total-= amount}

Although React is flexible, it has a strict rule:

Note: all React components must be pure functions and it is forbidden to modify their own props.

Of course, the application of UI is always dynamic and can be changed at any time.

If we want to change the UI dynamically, then it will involve the state we mentioned above. We render the entire page by dynamically changing the state, which we'll talk about later.

These are all the contents of the article "how to create components in React". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report