【问题标题】:Why decorator throws error of invalid type为什么装饰器会抛出无效类型的错误
【发布时间】:2019-06-08 15:29:35
【问题描述】:

小例子:

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 警告:React.createElement:类型无效 -- 期望一个字符串(用于内置组件)或一个类/函数(用于复合组件)但得到:.你有没有不小心 导出 JSX 文字而不是组件?

react-dom.development.js:55 未捕获错误:元素类型无效: 期望一个字符串(对于内置组件)或一个类/函数(对于 复合组件)但得到:对象。

当我从组件顶部移除装饰器时,一切正常。


babel 配置:

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

我的装饰器有什么问题?

【问题讨论】:

  • 请出示您的装饰器的进口声明。
  • 我没有,名字是:decorator,我在组件上面实现了。
  • 请检查我的答案

标签: javascript reactjs babeljs


【解决方案1】:

返回JSX 代码不是一个有效的表达式,你应该尝试用这样的类包装。

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

      componentDidMount() {

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-04
    • 2019-12-07
    • 1970-01-01
    • 1970-01-01
    • 2018-11-09
    • 2016-04-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多