为什么在React Component构造函数中的console.log(super)会抛出错误?

sli*_*wp2 4 javascript ecmascript-6 reactjs

我想super在我的InheritComponent constructor方法中安装.但是在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
)
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

以上是我的演示代码.

Kar*_*lak 6

原因很简单:super是关键字,不是函数,也不是任何变量.您无法记录super相同的内容,因为您无法记录varnew关键字.

如果要记录父项的构造函数,可以尝试:

console.log(super.constructor);
Run Code Online (Sandbox Code Playgroud)

事实上,super()这只是简写super.constructor().

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