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

What are the practical skills for developing React applications

2025-03-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article will explain in detail what are the practical skills for developing React applications, and the content of the article is of high quality, so the editor will share it with you for reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.

Background

Hooks has been very popular since its launch. It has changed the way we write React code and helps us write more concise code.

Text

1. Use a string to define a React element

Take a simple example:

/ / We can assign a string'p'to a variable, such as: import React from 'react'const MyComponent =' p'function App () {return (I am inside a {'} element)}

React.createElement is called internally in React and this string is used to generate the element.

Alternatively, you can explicitly define component to determine what is rendered, such as:

/ / define a MyComponentfunction MyComponent ({component: Component = 'paired, name, age, email}) {return (Hi {name} You are {age} years old Your email is {email})}

Applicable method:

Function App () {return ()}

In this way, you can also pass in a custom component, such as:

Function Dashboard ({children}) {return ({children})

)} function App () {return ()}

If you come across dealing with a similar class of elements or components, you can abstract it in this custom way to simplify your code.

Let's take a realistic example:

For example, we need to make a requirement for packing goods, either individually or in batches, and we can write custom components according to the common points:

Import React from 'react'import withTranslate from' @ components/withTranslate'import PackComponent from'. / PackComponent'import usePack, {check} from'. / usePack'let PackEditor = (props) = > {const packRes = usePack (props) return ()} PackEditor = withTranslate (PackEditor) PackEditor.check = checkexport default PackEditor

In this way, it can be used flexibly in different business modules, which is very convenient.

two。 Define error boundaries

In Javascript, we all use try/catch to catch possible exceptions and handle errors in catch. For example:

Function getFromLocalStorage (key, value) {try {const data = window.localStorage.get (key) return JSON.parse (data)} catch (error) {console.error}}

In this way, even if something goes wrong, our application will not crash the white screen.

In the final analysis, React is also Javascript, which is essentially no different, so there is no problem with using try/catch in the same way.

However, due to the React implementation mechanism, Javascript errors that occur within the component can break the internal state, and render will generate errors:

Https://github.com/facebook/react/issues/4026

For the above reasons, the React team introduced Error Boundaries:

Https://reactjs.org/docs/error-boundaries.html

Error boundaries is actually a React component, and you can find a component to handle any error messages it catches.

When the component tree crashes, you can also display your custom UI as a fallback.

Look at the official example provided by React: https://reactjs.org/docs/error-boundaries.html#introducing-error-boundaries

Class ErrorBoundary extends React.Component {constructor (props) {super (props) this.state = {hasError: false}} static getDerivedStateFromError (error) {/ / Update state so the next render will show the fallback UI. Return {hasError: true}} componentDidCatch (error, errorInfo) {/ / You can also log the error to an error reporting service logErrorToMyService (error, errorInfo)} render () {if (this.state.hasError) {/ / You can render any custom fallback UI return Something went wrong. } return this.props.children}}

Mode of use:

Live Demo By Dan Abramov:

Https://codepen.io/gaearon/pen/wqvxGa?editors=0010

3. High-order component

In popular terms, the so-called high-level component is that you throw a component in, add some properties or operations, and then throw it out.

In general, you can abstract some components that have something in common into a high-level component and reuse it in different modules.

For example, in our system, there is a kind of button that needs to add a border, which is used in many places, and we abstract it out:

Import React from 'react'// Higher order componentconst withBorder = (Component, customStyle) = > {class WithBorder extends React.Component {render () {const style = {border: this.props.customStyle? This.props.customStyle.border: '3px solid teal'} return}} return WithBorder} function MyComponent ({style,... rest}) {return (This is my component and I am expecting some styles.

)} export default withBorder (MyComponent, {border: '4px solid teal'})

The MyComponent component decorated by withBorder has the function of unified border. Later, if you want to make changes, you can handle it uniformly in this middle layer, which is very convenient.

In my project, I also used some high-level components, to give a specific example:

PackEditor = withTranslate (PackEditor)

Our PackEditor is an enhanced component. What functions have been added?

As the name suggests, withTranslate has added a translation function. Let's see how this component is implemented:

Import React from 'react'import {Provider} from' react-redux'import {injectIntl} from 'react-intl'import {store} from' @ redux/store'import {Intl} from'. / Locale'const withTranslate = BaseComponent = > (props) = > {/ / avoid create a new component on re-render const IntlComponent = React.useMemo (() = > injectIntl (({intl) . others}) = > ({/ / injection translation method if (! id) {return''} return intl.formatMessage (typeof id = 'string'? {id}: id, values)}} {... others} / >) []) IntlComponent.displayName = `withTranslate (${BaseComponent.displayName | | 'BaseComponent'}) `return ()} export default withTranslate

The usage is very clever:

Const Editor = withTranslate ({/ /... Translate,}) = > {/ /... Return ({translate ('xxx')}})})

It's very convenient.

4. Render props

Rrender prop refers to a simple technique of sharing code between React components using prop with a value as a function. Similar to HOC, it is a problem of logic reuse between components.

More specifically, Render prop is a function that tells the component what to render.

Let's look at a simple example:

The following components track the mouse position in the Web application:

Class Mouse extends React.Component {state = {x: 0, y: 0}; handleMouseMove = (event) = > {this.setState ({x: event.clientX, y: event.clientY});} render () {return (

The current mouse position is ({this.state.x}, {this.state.y})

);}} class MouseTracker extends React.Component {render () {return (move mouse);}}

As the cursor moves over the screen, the component displays its (xmemy) coordinates.

The question now is:

How do we reuse this behavior in another component?

In other words, if another component needs to know the mouse location, can we encapsulate this behavior so that we can easily share it with other components?

Suppose the product wants a feature to present a picture of a cat chasing a mouse on the screen.

We might use {this.setState ({x: event.clientX, y: event.clientY});} render () {return (

);}}

Bash ~ simple and rough, finish the task in one minute.

But what if you want to add a dog to the product next time?

The above example, although it can meet the requirement of cat chasing mouse, has not yet achieved the goal of truly encapsulating behavior in a reusable way.

When we want the mouse position to be used for different use cases, we must create a new component that presents something specifically for that use case.

This is also the origin of render prop:

We can provide a component with the function prop that dynamically determines what needs to be rendered instead of hard-coding it into the component.

Modify the above code:

Class Cat extends React.Component {render () {const mouse = this.props.mouse; return (

);}} class Mouse extends React.Component {state = {x: 0, y: 0}; handleMouseMove = (event) = > {this.setState ({x: event.clientX, y: event.clientY});} render () {return ({this.props.render (this.state)}

);}} class MouseTracker extends React.Component {render () {return (

Move the mouse! ()} / >

);}}

Provides a render method that lets you dynamically decide what needs to be rendered.

In fact, render prop is called render prop because of the pattern, and you don't have to use a prop named render to use this pattern.

Any function prop that tells the component what to render can technically be called "render prop".

In addition, an interesting thing about render prop is that you can use regular components with render prop to implement most high-level components (HOC).

For example, if you prefer to use withMouse HOC rather than components, you can easily create one using regular with render prop:

Function withMouse (Component) {return class extends React.Component {render () {return (()} / >);}

It is also very concise and clear.

It is important to note that if you create a function in a defined render function, using render prop will offset the advantages of using React.PureComponent.

Because you always get false when you compare props, and in this case each render will generate a new value for render prop.

Class Mouse extends React.PureComponent {/ / same code as above.} class MouseTracker extends React.Component {render () {return ((/ / this is not good! The value of each rendered `render` prop will be different. )} / >);}}

In such an example, each time it is rendered, it generates a new function as prop, thus offsetting the effect of components inherited from React.PureComponent.

To get around this problem, sometimes you can define a prop as an instance method, like this:

Class MouseTracker extends React.Component {renderTheCat (mouse) {return;} render () {return (

Move the mouse around!

);}} on the development of React applications what practical skills are shared here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

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: 255

*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

Development

Wechat

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

12
Report