javascript 反应片段速记无法编译
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48316365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
React fragment shorthand failing to compile
提问by Robert Byrne
The project in question is using React-16.2.0 which has the capability to use Fragments and the Fragment shorthand.
有问题的项目正在使用 React-16.2.0,它能够使用 Fragment 和 Fragment 速记。
https://reactjs.org/blog/2017/11/28/react-v16.2.0-fragment-support.html
https://reactjs.org/blog/2017/11/28/react-v16.2.0-fragment-support.html
While the full-length syntax works fine...
虽然全长语法工作正常......
import React, { Fragment, Component } from 'react';
class TestingFragment extends Component {
render() {
return (
<Fragment>
<span>This is a fragment of text </span>
<div>Another part of the fragment</div>
</Fragment>
)
}
};
export default TestingFragment
The shorthand fails to compile and I am at a loss as to why this is. Fore example...
速记无法编译,我不知道为什么会这样。例如...
import React, { Component } from 'react';
class TestingFragment extends Component {
render() {
return (
<>
<span>This is a fragment of text </span>
<div>Another part of the fragment</div>
</>
)
}
};
export default TestingFragment
Which fails to compile as follows...
无法编译如下...
Failed to compile
./src/testingFragments.js
Syntax error: Unexpected token (6:4)
4 | render() {
5 | return (
> 6 | <>
| ^
7 | <span>This is a fragment of text </span>
8 | <div>Another part of the fragment</div>
9 | </>
This error occurred during the build time and cannot be dismissed.
Is there something here I am missing about the Fragment shorthand syntax?
这里有什么关于 Fragment 速记语法的遗漏吗?
采纳答案by KORA
I think this is a reason:
我认为这是一个原因:
https://reactjs.org/blog/2017/11/28/react-v16.2.0-fragment-support.html#support-for-fragment-syntax
https://reactjs.org/blog/2017/11/28/react-v16.2.0-fragment-support.html#support-for-fragment-syntax
create-react-apps currently use Babel 6.26.0for full support React.Fragment is needed Babel v7.0.0-beta.31and above
create-react-apps 目前使用Babel 6.26.0来全面支持 React.Fragment 需要Babel v7.0.0-beta.31及以上
======================= EDIT
======================== 编辑
It's working now with create-react-app v2 https://reactjs.org/blog/2018/10/01/create-react-app-v2.html
它现在与 create-react-app v2 https://reactjs.org/blog/2018/10/01/create-react-app-v2.html 一起使用
回答by Shariq Ansari
Fragment syntax is only supported by Babel v7.0.0-beta.31 & above.
Fragment 语法仅支持 Babel v7.0.0-beta.31 及以上版本。
回答by gazdagergo
You can use the poor man'sfragment shorthand as a quick fix: [,]
您可以使用穷人的片段速记作为快速修复:[,]
render(){
return [
<div>foo</div>,
<div>bar</div>
]
}
as array is totally a valid jsx element.
因为数组是完全有效的 jsx 元素。

