Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJs, the SyntaxError with `static defaultProps`

Tags:

reactjs

I use the React to write this demo. I use the Webpack to build this demo.When I start this demo, the error will show me.

ERROR in ./src/app.js Module build failed: SyntaxError: Unexpected token (8:24)

 import React, {Component} from 'react';
    import ReactDOM from 'react-dom';
class Button extends Component {
    constructor(props){
        super(props);

    }
    static defaultProps = {
        color:'blue',
        text: 'Confirm',
    }
    render (){
        return (
            <button className={'btn btn-${color}'}>
                <em>{text}</em>
                <p>This is a button.</p>
            </button>
        );
    }
}
ReactDOM.render(<Button />, document.getElementById('app'));

I read this demo from a book. Due to the book is probably print the wrong code. So I ask this question now.

The error show static defaultProps = { is not right. The book is also written with this form. Do you know the right code?

like image 704
jiexishede Avatar asked Dec 27 '16 07:12

jiexishede


Video Answer


2 Answers

The terminal executes npm install --save-dev babel-preset-stage-0 in the current directory.

Add stage-0 to the current directory * .babelrc * file

{ "Presets": ["react", "es2015", "stage-0"], }}

like image 182
jiexishede Avatar answered Sep 25 '22 07:09

jiexishede


It could be some error in your webpack setup. Otherwise defaultProps is defined correctly as it should be.

One more thing to access the props you need to use this.props.propName

Check the below code -

class Button extends React.Component {
    constructor(props){
        super(props);

    }
    static defaultProps = {
        color:'blue',
        text: 'Confirm'
    }
    render (){
        return (
            <button className={'btn btn-${this.props.color}'}>
                <em>{this.props.text}</em>
                <p>This is a button.</p>
            </button>
        );
    }
}
ReactDOM.render(<Button />, document.getElementById('app'));
<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>
<div id="app"></div>
like image 30
WitVault Avatar answered Sep 23 '22 07:09

WitVault