gpt4 book ai didi

javascript - 为什么装饰器会抛出无效类型的错误

转载 作者:行者123 更新时间:2023-12-01 01:21:29 30 4
gpt4 key购买 nike

最小示例:

import React from 'react';
import ReactDOM from 'react-dom';


const decorator = context => WrappedComponent => <WrappedComponent context={context}/>;

@decorator(1)
class Parent extends React.Component {
render(){
return 1;
}
}

ReactDOM.render(<Parent />, document.getElementById('app-root'));

错误:

react.development.js:225 Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: . Did you accidentally export a JSX literal instead of a component?

react-dom.development.js:55 Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

当我从组件顶部删除装饰器时,一切都运行良好。

<小时/>

巴贝尔配置:

"plugins": [
[
"@babel/plugin-proposal-decorators",
{
"legacy": true
}
]
]

我的装饰器有什么问题?

最佳答案

返回的 JSX 代码不是有效的表达式,您应该尝试包装在这样的类中。

const decorator = (providedContext) => (WrappedComponent) => {
return class extends React.Component {

componentDidMount() {

}
render() {
return <WrappedComponent context={providedContext}/>
}
}
}

关于javascript - 为什么装饰器会抛出无效类型的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54184974/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com