reactjs - 为什么这个 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>
解决方案
您没有正确使用 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>
推荐阅读
- typescript - 打字稿:为什么这个微不足道的泛型函数不像它的非泛型等效函数?
- html - 必需和检查的输入标签在 Angular 组件中不起作用
- html - 难以实现 vue 分页
- javascript - 关于使用 Vanilla JS 的小屏幕上的滚动动画问题
- karate - 在空手道中转换日期格式
- php - 错误:SQLSTATE[08001]:[Microsoft][ODBC Driver 17 for SQL Server]客户端不支持加密
- asp.net-core - 如何将新列添加到 Identity RoleClaims 表中(asp net core)
- events - 为什么当我尝试使用 Google Tag Manager 跟踪时,Google Analytics 中的出站链接等于“(未设置)”?
- javascript - 原生 JS Promise 重试包装器
- azure - Azure 数据流需要几分钟才能触发下一个管道