【发布时间】:2020-01-12 03:19:44
【问题描述】:
我创建了一个示例项目来演示我在尝试同时使用两个高阶组件 (hoc) 时遇到的问题。
首先是孤立的(没有错误)
=================================
第一个 hoc withStuff 接受一个注入的参数和一个 prop 并将 sum 传递给包装的组件。
// withStuff.js
const withStuff = ({argNumber}) => (BaseComponent) => ({propNumber, ...passThroughProps}) => {
const sum = argNumber+propNumber
return <BaseComponent sum={sum} {...passThroughProps} />
}
export default withStuff
第二个 hoc withExtra 采用注入函数并将结果加倍,将 double 传递给包装的组件。
// withExtra.js
const withExtra = (extraFunction) => (BaseComponent) => ({...passThroughProps}) => {
const double = 2*extraFunction()
return <BaseComponent double={double} {...passThroughProps} />
}
export default withExtra
这就是 Base 组件的使用方式,例如 withStuff(到目前为止一切正常)。
// Base.js
import withStuff from './withStuff'
const Base = ({content, sum}) => <div>{content} -sum:{sum}</div>
export default withStuff({argNumber:2})(Base)
==================================
现在问题来了:尝试在withStuff 中使用withExtra:
import withExtra from './withExtra'
const withStuff = ({argNumber}) => (BaseComponent) => ({propNumber, ...passThroughProps}) => {
const sum = argNumber+propNumber
// this does not work
return withExtra(()=>sum)(<BaseComponent sum={sum} {...passThroughProps}/>)
}
export default withStuff
这会返回一个错误:
Warning: Functions are not valid as a React child.
是不是因为现在withStuff 返回的是一个 hoc 函数而不是一个组件?该函数本身返回一个组件,所以我看不到问题所在。如何解决?
【问题讨论】:
标签: reactjs react-redux higher-order-components