当我使用React-Native默认打包程序启动项目时,我遇到此错误:Unexpected token
在此行:
static propTypes = {
/// ...
};
我在GitHub上查看了React-Native问题,但我没有找到解决方案。
有什么建议吗?
答案 0 :(得分:7)
React-Native包装程序使用Babel进行传输ES6和ES7,但不是所有功能。启用列表为here。在您的情况下,RN packager中默认情况下未启用class-props。您可以使用Babel在打包程序之前编译代码,或者只在打包程序设置中启用它。有关详细信息,请参阅此official doc。
答案 1 :(得分:4)
尝试将propTypes附加到您的班级:
var MyClass extends React.Component {
....
}
MyClass.propTypes = {
.... /* enter proptypes here */
}
答案 2 :(得分:3)
@Fomahaut回答后,我一直在Facebook的GitHub存储库上查找并发现此问题:https://github.com/facebook/react-native/issues/2182
示例:
{
"retainLines": true,
"compact": true,
"comments": false,
"whitelist": [
"es6.arrowFunctions",
"es6.blockScoping",
"es6.classes",
"es6.constants",
"es6.destructuring",
"es6.forOf",
"es6.modules",
"es6.parameters",
"es6.properties.computed",
"es6.properties.shorthand",
"es6.spread",
"es6.tailCall",
"es6.templateLiterals",
"es6.regex.unicode",
"es6.regex.sticky",
"es7.asyncFunctions",
"es7.classProperties",
"es7.comprehensions",
"es7.decorators",
"es7.exponentiationOperator",
"es7.exportExtensions",
"es7.functionBind",
"es7.objectRestSpread",
"es7.trailingFunctionCommas",
"regenerator",
"flow",
"react",
"react.displayName"
],
"sourceMaps": false
}
答案 3 :(得分:3)
根据this answer,您需要为Babel 6中的类属性安装插件。
截至Babel 6,您现在需要transform-class-properties插件 支持类属性。
步骤:
npm install babel-plugin-transform-class-properties
"plugins": ["transform-class-properties"]
(注意,它是一个插件,而不是转换;所以不要把它放在" presets"列表中。)为我工作。
答案 4 :(得分:1)
安装stage-0 Babel preset(npm i --save-dev babel-preset-stage-0
)并将其添加到.babelrc
文件的presets
部分,例如:
{ "presets": ["react", "es2015", "babel-preset-stage-0"] }
答案 5 :(得分:0)
看看是否有帮助:
$ npm install babel-plugin-transform-decorators
/<your project root>/node_modules/react-native/packager/react-packager/.babelrc
将"transform-decorators"
添加到此列表中:
{
"retainLines": true,
"compact": true,
"comments": false,
"plugins": [
"syntax-async-functions",
"syntax-class-properties",
"syntax-trailing-function-commas",
"transform-class-properties",
"transform-es2015-arrow-functions",
"transform-es2015-block-scoping",
"transform-es2015-classes",
"transform-es2015-computed-properties",
"transform-es2015-constants",
"transform-es2015-destructuring",
["transform-es2015-modules-commonjs", {"strict": false, "allowTopLevelThis": true}],
"transform-es2015-parameters",
"transform-es2015-shorthand-properties",
"transform-es2015-spread",
"transform-es2015-template-literals",
"transform-flow-strip-types",
"transform-object-assign",
"transform-object-rest-spread",
"transform-react-display-name",
"transform-react-jsx",
"transform-regenerator",
"transform-es2015-for-of",
-->"**transform-decorators**"<--
],
"sourceMaps": false
}