【问题标题】:Direct super call is illegal in non-constructor, use super."constructor"() instead在非构造函数中直接调用 super 是非法的,使用 super."constructor"() 代替
【发布时间】:2023-04-09 21:32:01
【问题描述】:
  • 我是新手,正在尝试编写一个简单的点击事件功能。

  • 当我点击选择这个类名的 span 标签时

  • 我在 codepen 中编写了一个小型原型,它在那里工作正常...
  • 但如果我在我的代码库中加入相同的代码,则会引发错误...
  • 你们知道是什么问题吗
  • 即使在 codepen 中也会显示错误 未知:类构造函数之外的 super() (16:8)

工作的小型原型代码 http://codepen.io/anon/pen/rxPvyr?editors=0110

尝试修复错误的实际代码库 http://codepen.io/kk-/pen/BjeLry

Line 16: Direct super call is illegal in non-constructor, use super."constructor"() instead
  14 | 
  15 |     constructor(props) {
> 16 |         super(props);
     |         ^
  17 |         
  18 |         this.handleClick = this.handleClick.bind(this);

【问题讨论】:

  • 为什么在使用React.createClass 时要定义constructorcreateClass 模式会为您自动绑定。
  • @mathletics 感谢您的回复...您可以在 codepen 中更新它如此混乱:(
  • 阅读文档:facebook.github.io/react/docs/component-specs.html;您将 ES6 类模式与 React 工厂模式混为一谈。
  • @mathletics 我正在阅读它......如果你更新 codepen 会很棒

标签: javascript html css reactjs


【解决方案1】:

有几种惯用的方式来定义 React 类 - 您可能混合和匹配样式,当然不支持这种方式:


ES5 - 没有constructor() 方法,使用getInitialState()

var React = require('react');

var SomeComponent = React.createClass({
    getInitialState: function() {
        return { message: 'hello world'};
    },
    render() {
        return (
            <div>{this.state.message}</div>
        );
    }
});

module.exports = SomeComponent;

ES6 - 否 getInitialState(),使用 constructor() 此外,您必须在调用 this 之前调用 super(props)

import React from 'react';

class SomeComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state({
            message: 'hello world'
        })
    }
    render() {
        return (
            <div>{this.state.message}</div>
        );
    }
}

SomeComponent.propTypes = {};

export default SomeComponent;

更新:如果忘记在constructor()中调用super(props),然后尝试访问this,则会抛出以下错误:'this' is not allowed before super()

Module build failed: SyntaxError: C:/_workspaces/hello-world/some-component.jsx: 'this' is not allowed before super()
  20 | class SomeComponent extends React.Component {
  21 |     constructor(props) {
> 22 |         this.state = {
     |         ^
  23 |             message: 'hello world'
  24 |         }
  25 |     }

这里有一些关于为什么需要它的更多信息:https://discuss.reactjs.org/t/should-we-include-the-props-parameter-to-class-constructors-when-declaring-components-using-es6-classes/2781


ES6 静态没有内部方法,只是一个隐含的render()

import React from 'react';

const SomeComponent = ({
    message
}) => (
    <div>{message}</div>
);

SomeComponent.propTypes = {};

export default SomeComponent;

【讨论】:

  • @texirv 没问题,不要让模组打败你。我们都去过那里......他们似乎有时会忘记......
  • 我还有一个问题,如果我们不在 es6 中调用 super(props) 会发生什么
  • @texirv 好问题,我已经更新了答案来解决这一点。
猜你喜欢
  • 1970-01-01
  • 2012-05-17
  • 2013-02-18
  • 2018-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多