[英]What is the form of Javascript used in this class declaration?
This is from the table example from React-toolbox (which could use a tag) 这是来自React-toolbox的表格示例 (可以使用标签)
class TableTest extends React.Component {
state = { selected: [], source: users };
handleSelect = (selected) => {
this.setState({selected});
};
render () {
return (
<Table
model={UserModel}
onSelect={this.handleSelect}
selectable
multiSelectable
selected={this.state.selected}
source={this.state.source}
/>
);
}
}
This does not compile with webpack/babel for me but the following 'correct' Javascript does. 这不能用webpack / babel编译,但是下面的'正确'的Javascript确实如此。 Is this JSX notation and a sign that I'm not transpiling JSX as I think I am?
这是JSX表示法,并且表明我没有像我想的那样转发JSX吗?
class TableTest extends React.Component {
constructor() {
super();
this.state = { selected: [], source: users };
this.handleSelect = (selected) => {
this.setState({selected});
};
}
render () {
return (
<Table
model={UserModel}
onSelect={this.handleSelect}
selectable
multiSelectable
selected={this.state.selected}
source={this.state.source} />
);
}
}
Webpack/babel chokes on: Webpack / babel chokes on:
ERROR in ./src/client/app/app.jsx
Module build failed: SyntaxError: Unexpected token (21:8)
19 |
20 | class TableTest extends React.Component {
> 21 | state = { selected: [], source: users };
This is using class properties , which are currently part of Babel's stage 2 preset . 这是使用类属性 ,它们是Babel第2阶段预设的一部分 。
For this code, the =
statements in the class body would get moved into the constructor by the class properties transform. 对于此代码,类主体中的
=
语句将通过类属性转换移动到构造函数中。
Here's the original code in the Babel REPL with suitable presets applied . 这是Babel REPL中的原始代码,其中应用了适当的预设 。
You will need to add this preset (or a lower stage preset, as all Babel stage presets also include higher stage features) to your Babel config, or add the transform plugin to it individually. 您需要将此预设(或较低阶段预设,因为所有Babel舞台预设还包括更高阶段功能)添加到您的Babel配置,或单独添加转换插件。
Example Babel config which would provide all the features you need to transpile the original code: 示例Babel配置,它将提供转换原始代码所需的所有功能:
{
presets: ['es2015', 'react', 'stage-2']
}
It's throwing an error on the =
declaration inside of the class. 它在类内部的
=
声明中抛出错误。 You need to bind this
to handleSelect
due to React's no autobinding rule. 由于React没有自动绑定规则,您需要
this
绑定到handleSelect
。
https://facebook.github.io/react/docs/reusable-components.html#no-autobinding https://facebook.github.io/react/docs/reusable-components.html#no-autobinding
class TableTest extends React.Component {
constructor(props) {
super(props);
this.state = {
selected: [], source: users
};
this.handleSelect = this.handleSelect.bind(this);
}
handleSelect(selected) {
this.setState({selected});
}
render () {
return (
<Table
model={UserModel}
onSelect={this.handleSelect}
selectable
multiSelectable
selected={this.state.selected}
source={this.state.source}
/>
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.