react高阶组件_React高阶组件

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的要旨。

翻译自: https://flaviocopes.com/react-higher-order-components/

react高阶组件

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值