首页 > 解决方案 > 为什么这个 HOC 类不会在 React 中返回渲染的子组件?

问题描述

我有以下代码包装了一个用于为子组件提供上下文的函数,但是,当我尝试渲染它时,它失败了,我的包装组件不渲染,在 React 16.6.3

import React from 'react'

export const WishlistContext = React.createContext(null)


const AddToWishListButtonWrapper = (WrappedComponent) => {
  return class WishlistButton extends React.Component {
    state = {token: null, wishlistItems: []}
    render() {
      const {token, wishlistItems} = this.state
      return (
        <WishlistContext.Provider value={wishlistItems}>
          <WrappedComponent {...this.props} />
        </WishlistContext.Provider>
      )
    }
  }
}

export default AddToWishListButtonWrapper

然后在我的另一个组件中,它看起来像这样:

import AddToWishListButtonWrapper from 'src/components/wishlist_button'

...

      <AddToWishListButtonWrapper>
        <WishlistButton>
          {'   '}{wishlistSuccess ? 'Added!' : 'Add to Wishlist'}
        </WishlistButton>
      </AddToWishListButtonWrapper>

但是,如果我在组件和 JSX 中使用导入将以下更改为小写,则不会呈现任何内容,则包装的组件会呈现,而不会触发任何生命周期方法,这令人费解。

import addToWishListButtonWrapper from 'src/components/wishlist_button'

          <addToWishListButtonWrapper>
            <WishlistButton>
              {'   '}{wishlistSuccess ? 'Added!' : 'Add to Wishlist'}
            </WishlistButton>
          </addToWishListButtonWrapper>

标签: reactjsjsx

解决方案


您没有正确使用 HOC。您需要创建组件的实例,例如

import React from 'react'

export const WishlistContext = React.createContext(null)


const AddToWishListButtonWrapper = (WrappedComponent) => {
  return class WishlistButton extends React.Component {
    state = {token: null, wishlistItems: []}
    render() {
      const {token, wishlistItems} = this.state
      return (
        <WishlistContext.Provider value={wishlistItems}>
          <WrappedComponent {...this.props} />
        </WishlistContext.Provider>
      )
    }
  }
}

export default AddToWishListButtonWrapper

const MyComp = () => (
   <WishlistButton>
        {'   '}{wishlistSuccess ? 'Added!' : 'Add to Wishlist'}
   </WishlistButton>
)
const WrapComponent = AddToWishListButtonWrapper(MyComp)

并将其渲染为

<WrapComponent />

或者代替 HOC 你可以使用render props pattern类似的

import React from 'react'

export const WishlistContext = React.createContext(null)


const AddToWishListButtonWrapper = (WrappedComponent) => {
  return class WishlistButton extends React.Component {
    state = {token: null, wishlistItems: []}
    render() {
      const {token, wishlistItems} = this.state
      const { children } = this.props;
      return (
        <WishlistContext.Provider value={wishlistItems}>
          {children()}
        </WishlistContext.Provider>
      )
    }
  }
}

export default AddToWishListButtonWrapper

<AddToWishListButtonWrapper>
     {() => (
        <WishlistButton>
          {'   '}{wishlistSuccess ? 'Added!' : 'Add to Wishlist'}
        </WishlistButton>
     )}
</AddToWishListButtonWrapper>

推荐阅读