为什么React组件中的console.log(super)会抛出一个错误

Why console.log(super) in React Component constructor throw an Error?

本文关键字:错误 一个 super 组件 React log console 为什么      更新时间:2023-09-26

我想在我的InheritComponent constructor方法中安慰super。但在chrome控制台,它抛出一个错误。为什么?

class BaseComponent extends React.Component{
    static defaultProps = {
        title: 'Learn React By Examples'
    }
    constructor(props) {
        console.log(props);
        super(props);
    }
    setTitle(title) {
        document.title = title || this.props.title;
        return document.title;
    }
}
class InheritComponent extends BaseComponent{
  
    state = {
      title: ''
    };
    constructor(props) {
        super(props);
        
        //here throw an Error. Why? I want to console.log `super`
        console.log(super);
    }
    componentDidMount() {
        const title = this.setTitle('组件继承')
        this.setState({title});
    }
    render() {
        return <div>
            <p>I inherit BaseComponent</p>
            <p>current title is {this.state.title}</p>
            
        </div>
    }
}
ReactDOM.render(
  <InheritComponent />,
  document.body
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

以上是我的演示代码

原因很简单:super是关键字,不是函数,也不是变量。supervarnew关键字一样不能记录。

如果你想记录父类的构造函数,你可以试试:

console.log(super.constructor);

实际上,super()只是super.constructor()的简写。

查看更多:https://developer.mozilla.org/pl/docs/Web/JavaScript/Reference/Operators/super

super是一个关键字,你不能像使用变量一样使用它。唯一允许使用super的方法在MDN文档中列出:

超级((参数));//调用父构造函数

super.functionOnParent((参数));

如果你想打印父类,使用console.log(super.constructor)

相关文章: