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?
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"],
}}
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With