react高阶组件
You might be familiar with Higher Order Functions in JavaScript. Those are functions that accept functions as arguments, and/or return functions.
您可能熟悉JavaScript中的高阶函数。 这些是接受函数作为参数和/或返回函数的函数。
Two examples of those functions are Array.map()
or Array.filter()
.
这些函数的两个示例是Array.map()
或Array.filter()
。
In React, we extend this concept to components, and so we have a Higher Order Component (HOC) when the component accepts a component as input and returns a component as its output.
在React中,我们将此概念扩展到组件,因此当组件接受一个组件作为输入并返回一个组件作为其输出时,我们就有了一个高阶组件(HOC) 。
In general, higher order components allow you to create code that’s composable and reusable, and also more encapsulated.
通常,高阶组件使您可以创建可组合和可重用的代码,并且还可以封装更多的代码。
We can use a HOC to add methods or properties to the state of a component, or a Redux store for example.
我们可以使用HOC将方法或属性添加到组件或Redux存储的状态。
You might want to use Higher Order Components when you want to enhance an existing component, operate on the state or props, or its rendered markup.
当您要增强现有组件,对状态或道具或其渲染标记进行操作时,可能需要使用高阶组件。
There is a convention of prepending a Higher Order Component with the with
string (it’s a convention, so it’s not mandatory), so if you have a Button
component, its HOC counterpart should be called withButton
.
有一个约定,在with
字符串的前面放置一个高阶组件(这是一个约定,因此不是必须的),因此,如果您有一个Button
组件,则其HOC对应项应称为withButton
。
Let’s create one.
让我们创建一个。
The simplest example ever of a HOC is one that returns the component unaltered:
HOC最简单的示例是返回未更改的组件的示例:
const withElement = Element => () => <Element />
Let’s make this a little bit more useful and add a property to that element, in addition to all the props it already came with, the color:
让我们使其更加有用,并为该元素添加一个属性,除了它已经附带的所有道具之外,还包括颜色:
const withColor = Element => props => <Element {...props} color="red" />
We use this HOC in a component JSX:
我们在组件JSX中使用此HOC:
const Button = () => {
return <button>test</button>
}
const ColoredButton = withColor(Button)
and we can finally render the WrappedButton component in our app JSX:
最后,我们可以在应用程序JSX中呈现WrappedButton组件:
function App() {
return (
<div className="App">
<h1>Hello</h1>
<ColoredButton />
</div>
)
}
This is a very simple example but hopefully you can get the gist of HOCs before applying those concepts to more complex scenarios.
这是一个非常简单的示例,但是希望您可以在将这些概念应用于更复杂的场景之前了解HOC的要旨。
react高阶组件