我在 React js 中使用 Babel。问题是我不想将 es6 转换为 es5。我想继续使用es6。我只需要将 jsx 转换为 js。这是我的 .babelrc
{
"plugins": ["transform-react-jsx"]
}
这是我的代码:
import React from "react";
/****** Header *******/
export class Header extends React.Component {
onSubmit = (e) => {
e.preventDefault();
console.log('Submitting');
const errors = this.validate();
if (Object.keys(errors).length === 0) {
this.setState({ loading: true });
fetch(this.props.action, {
method: 'POST',
body: JSON.stringify(this.state.data),
headers: new Headers({
'Content-Type': 'application/json'
}),
credentials: 'same-origin'
}).then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
}
};
render() {
return (
<div>
<a href={this.props.homeUrl}><img src={this.props.logoUrl} /></a>
<div><span>Hello {this.props.userName}</span></div>
<button onclick={this.onSubmit(e).bind(this)}>Click me</button>
</div>
);
}
}
这是我在运行“babel components/Header.js -o Header.babel.js”时看到的
SyntaxError: components/Header.js: Unexpected token (5:13)
3 | /****** Header *******/
4 | export class Header extends React.Component {
> 5 | onSubmit = (e) => {
| ^
6 | e.preventDefault();
7 | console.log('Submitting');
8 | const errors = this.validate();
它向我展示了 es6 代码行的语法错误 所以我认为 Babel 仍然需要将 es6 转换为 es5
安装“transform-class-properties”后,它显示另一条错误消息:
SyntaxError: components/Form.js: Unexpected token (55:12)
53 | getFieldValue(e) {
54 | this.setState({
> 55 | ...this.state,
| ^
56 | data: {
57 | ...this.state.data,
58 | [e.target.name]: e.target.value
你知道有没有办法做到这一点?只将 JSX 转换为 JS
非常感谢你的支持