Home > Article > Web Front-end > Detailed explanation of using React high-order components
This time I will bring you a detailed explanation of the use of React high-end components. What are the precautions for using React high-end components? Here are practical cases, let’s take a look.
What is
A higher-order component is a function that accepts a component and returns a new component. There are no side effects.
Why use
to encapsulate and abstract the common logic of components so that this part of the logic can be better reused between components.
How to use
//hoc为我们的高阶组件,可以使用es7装饰器语法来使用高阶组件 //当然也可以不用es7,如:let hocHello = hoc(Hello),只是es7的语法更优雅一些。 //高阶组件可以叠加使用,可以对一个组件使用多个高阶组件 @hoc class Hello extends React.Component { // }
How to implement
Attribute proxy
The following example is the simplest An implementation
function hoc(ImportComponent) { return class Hoc extends React.Component { static displayName = `Hoc(${getDisplayName(ImportComponent)})` //displayName是设置高阶组件的显示名称 render() { return <ImportComponent {...this.props} /> } } } function getDisplayName(Component) { return Component.displayName || Component.name || "Component" }
Function: operate props, refs to obtain component instances
Notes: Static methods cannot be passed and must be copied manually; refs cannot be passed.
Reverse inheritance
The following example is the simplest implementation
export function hoc(ImportComponent) { return class Hoc extends ImportComponent { static displayName = `Hoc(${getDisplayName(ImportComponent)})` render() { return super.render() } } }
Function: Manipulate state; render hijack (operate its render function )
Note: By inheriting ImportComponent, in addition to some static methods, including life cycle, state, and various functions, we can get them.
Principle
Do not modify the original component. The higher-order component only wraps the sub-components in the container component through combination. It is an invisible component. Pure functions with side effects.
Don’t use higher-order components inside the render method.
Higher-order components can add functionality to components, but they should not drastically change functionality.
To facilitate debugging, choose a display name to indicate that it is the result of a higher-order component.
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:
How to operate JS to implement placeholder attribute prompt text in html
How to use JS countdown to restore button click Function
The above is the detailed content of Detailed explanation of using React high-order components. For more information, please follow other related articles on the PHP Chinese website!