我建立了一个HOC,并想用Styles包装它。但是随后出现以下错误。怎么了?
TypeError: Cannot call a class as a function
反应js
const withLoader = (loadingProp) => (WrappedComponent) => {
return class LoadIndicator extends Component {
render() {
return <h1>hello world</h1>
}
}
}
export default withStyles(styles)(withLoader)
答案 0 :(得分:1)
功能组件return
应该始终像render function
一样,返回值位于class components
中。
对您的代码进行修改应可解决您的错误。
class LoadIndicator extends Component {
render() {
return <h1>hello world</h1>
}
}
const withLoader = (loadingProp) => (WrappedComponent) => {
return <LoadIndicator />
}
export default withStyles(styles)(withLoader(loadingProp))
答案 1 :(得分:1)
您应该包装返回的组件而不是HOC函数:
const withLoader = (loadingProp) => (WrappedComponent) => {
return withStyles(styles)(class LoadIndicator extends Component {
render() {
return <h1>hello world</h1>
}
}}
}
export default (withLoader)
答案 2 :(得分:1)
此加载程序HOC需要使用加载标志的prop名称实例化。
我将假定HOC的样式适用于LoadIndicator
:
const withLoader = (loadingProp) => (WrappedComponent) => {
class LoadIndicator extends Component {
render() {
// Todo: render WrappedComponent and/or a loading element.
return <h1>hello world</h1>
}
}
return withStyles(styles)(LoadIndicator);
}
export default withLoader;
现在,当您使用此HOC时,您仍然需要指定称为load的属性:
withLoader('loading')(SomeComponent)