2016-08-15 3 views
3

Я хочу, чтобы консоль super в моем InheritComponentconstructor метод. Но в хром-консоли он бросает ошибку. Зачем?Почему console.log (super) в конструкторе React Component выдает ошибку?

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>

Выше мой демонстрационный код.

+0

Я думаю, что вы не можете добавить что-либо перед вызовом super, можете ли вы удалить инструкцию console.log и попробовать один раз? –

+0

@HarkiratSaluja удалить инструкцию console.log будет работать. Но я хочу утешить «супер». И, моя инструкция console.log после 'super (props)' statement – novaline

ответ

4

Причина проста: super - это ключевое слово, а не функция или переменная. Вы не можете зарегистрировать super так же, как вы не можете зарегистрировать var или new ключевых слов.

Если вы хотите, чтобы войти в конструктор родителя, вы можете попробовать:

console.log(super.constructor); 

На самом деле, super() просто сокращение для super.constructor().

Смотреть еще: https://developer.mozilla.org/pl/docs/Web/JavaScript/Reference/Operators/super

3

super является ключевое слово, вы не можете использовать его как переменную. Доступны только разрешенные способы использования супер: in the MDN documentation for it:

super ([arguments]); // вызывает родительский конструктор.

super.functionOnParent ([arguments]);

Если вы хотите напечатать родительский класс, вместо этого используйте console.log(super.constructor).

+0

Спасибо. Я видел документ. – novaline