我正在尝试创建HOC以包装模式,并且正在遇到此错误:A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.
我已经检查了其他几个线程,并且问题似乎是导入的 - 但是我认为这里并不是这样。这是我的代码:
create-modal.js
import { Component } from 'react'
import withRedux from 'next-redux-wrapper'
import Layout from '../../components/layouts/main'
import ModalContainer from './modal-container'
// Modal Layouts
import Empty from './empty'
import Basic from './basic'
const data = {
title: 'Silly Modal.',
layout: 'empty',
customClass: '',
multiStep: false,
steps: [
{
isVisible: true,
isAnimated: false,
animationName: null,
header: 'TEST',
currentContent: 'Testing the modal. What fun!',
buttons: {
closeText: 'Close',
closeAction: null,
continueText: null,
continueAction: null,
},
closeRedirect: null,
closeRedirectPath: null,
continueRedirect: null,
continueRedirectPath: null,
},
],
}
function newModal (WrappedComponent, data) {
if (!WrappedComponent && !data) return null
return class Modal extends Component {
constructor (props) {
super(props)
}
render () {
return (
<Layout>
<ModalContainer>
<WrappedComponent />
</ModalContainer>
</Layout>
)
}
}
}
console.log('what is newModal returning?!', (newModal(<Basic />, data)) )
export default newModal
console.loging呼叫此HOC的返回表明它正在返回一个函数,而不是组件:
function Modal(props) {
(0, _classCallCheck3.default)(this, Modal);
return (0, _possibleConstructorReturn3.default)(this, (Modal.__proto__ || (0, _getPrototypeOf2.default)(Modal)).call(this, props…
似乎是错误的。
我还应该注意,我可能会做错了这个返回(但不确定。但是,我尝试过以相同结果的return <WrappedComponent />
:(
我所导入的所有组件均以default
导出,因此我相信,在此处不使用括号在此处是正确的。我是HOC的新手,只是没有看到什么问题,因为我遵循我密切看到的模式。任何帮助都将不胜感激!
您正在使用此语句返回类构造函数:
return class Modal extends Component {
这就是为什么它抱怨
您可能只使用纯react组件,因为您似乎不需要道具或状态。
这将使您摆脱这个问题,但我怀疑您还是需要做不同的事情,因为它看起来好像要传递一个元素,并在模态包装器中渲染该元素。
查找如何使用{this.props.children}的线索,或者如果我在正确的轨道上,我可以为您提供更多帮助。
update
我认为您想做的就是利用孩子。您可以做这样的事情:
<ModalWrapper name="A modal dialog (which is generic and re-usable)">
<SomethingElse name="This is my custom component">
:
:
</SomethingElse>
</ModalWrapper>
在模拟器的渲染方法中,您只是渲染{this.props.children}
,它带来了您作为孩子的任何标记。
(我不是100%确定是否是{this.props.children},但是您会得到我的漂移
hoc是一个接收组件的函数,包装它以添加更多功能并返回另一个组件。这不是您可以将其用作代码中的组件。您使用它来增强现有组件。
您无法正确使用HOC组件,您应该这样做:
import Basic from './basic'
...
const NewModal = newModal(Basic, data)
...
render()
<NewModal ... />
查看官方反应文档的例子:https://reactjs.org/docs/higher-order-components.html