React片段速记无法编译

Rob*_*rne 21 javascript reactjs create-react-app

有问题的项目是使用React-16.2.0,它有能力使用Fragments和Fragment简写.

https://reactjs.org/blog/2017/11/28/react-v16.2.0-fragment-support.html

虽然全长语法工作正常...

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
Run Code Online (Sandbox Code Playgroud)

速记无法编译,我不知道为什么会这样.例子......

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
Run Code Online (Sandbox Code Playgroud)

哪个编译失败如下......

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.
Run Code Online (Sandbox Code Playgroud)

有没有关于Fragment简写语法的东西?

KOR*_*ORA 22

我认为这是一个原因:

https://reactjs.org/blog/2017/11/28/react-v16.2.0-fragment-support.html#support-for-fragment-syntax

截图

create-react-apps目前使用Babel 6.26.0 获得全面支持React.Fragment需要Babel v7.0.0-beta.31及以上版本

=======================编辑

它正在使用create-react-app v2 https://reactjs.org/blog/2018/10/01/create-react-app-v2.html

  • 尝试在代码中使用“ babel”独立版“ 7.1.0”,但仍然无法正常工作。 (2认同)

gaz*_*rgo 9

您可以使用穷人的片段速记作为快速修复:[ , ]

render(){
  return [
    <div>foo</div>,
    <div>bar</div>
  ]
}
Run Code Online (Sandbox Code Playgroud)

因为数组是完全有效的 jsx 元素。


Sha*_*ari 6

Fragment 语法仅支持 Babel v7.0.0-beta.31 及以上版本。