本文翻译自:Parse Error: Adjacent JSX elements must be wrapped in an enclosing tag

I am trying to set up my React.js app so that it only renders if a variable I have set is true. 我试图设置我的React.js应用程序,以便仅在我设置的变量为true时才呈现。

The way my render function is set up looks like: 我的渲染功能的设置方式如下:

render: function() {var text = this.state.submitted ? 'Thank you!  Expect a follow up at '+email+' soon!' : 'Enter your email to request early access:';var style = this.state.submitted ? {"backgroundColor": "rgba(26, 188, 156, 0.4)"} : {};return (<div>if(this.state.submitted==false)
{<input type="email" className="input_field" onChange={this._updateInputValue} ref="email" value={this.state.email} /><ReactCSSTransitionGroup transitionName="example" transitionAppear={true}><div className="button-row"><a href="#" className="button" onClick={this.saveAndContinue}>Request Invite</a></div></ReactCSSTransitionGroup>
}</div>)},

Basically, the important portion here is the if(this.state.submitted==false) portion (I want these divs to show up when the submitted variable is set to false). 基本上,这里的重要部分是if(this.state.submitted == false)部分(当提交的变量设置为false时,我希望这些div出现)。

But when running this, I get the error in the Question: 但是,运行此命令时,出现以下问题:

Uncaught Error: Parse Error: Line 38: Adjacent JSX elements must be wrapped in an enclosing tag 未捕获的错误:解析错误:第38行:相邻的JSX元素必须包装在一个封闭的标记中

What is the issue here? 这是什么问题? And what can I use to make this work? 我可以用什么做这项工作?


#1楼

参考:https://stackoom.com/question/27GRN/解析错误-相邻的JSX元素必须包装在一个封闭标签中


#2楼

React element has to return only one element. React元素只能返回一个元素。 You'll have to wrap both of your tags with another element tag. 您必须将两个标签都包装在另一个元素标签上。

I can also see that your render function is not returning anything. 我还可以看到您的渲染函数未返回任何内容。 This is how your component should look like: 这是您的组件的外观:

var app = React.createClass({render () {/*React element can only return one element*/return (<div></div>)}
})

Also note that you can't use if statements inside of a returned element: 还要注意,您不能在返回的元素内使用if语句:

render: function() {
var text = this.state.submitted ? 'Thank you!  Expect a follow up at '+email+' soon!' : 'Enter your email to request early access:';
var style = this.state.submitted ? {"backgroundColor": "rgba(26, 188, 156, 0.4)"} : {};if(this.state.submitted==false) {return <YourJSX />} else {return <YourOtherJSX />}
},

#3楼

You should put your component between an enclosing tag, Which means: 您应该将组件放在一个封闭标签之间,这意味着:

// WRONG!return (  <Comp1 /><Comp2 />
)

Instead: 代替:

// Correctreturn (<div><Comp1 /><Comp2 /></div>
)

Edit: Per Joe Clay's comment about the Fragments API 编辑: Per Joe Clay关于Fragments API的评论

// More Correctreturn (<React.Fragment><Comp1 /><Comp2 /></React.Fragment>
)

#4楼

It is late to answer this question but I thought It will add to the explanation. 回答这个问题为时已晚,但我认为这将增加解释。

It is happening because any where in your code you are returning two elements simultaneously. 之所以发生这种情况,是因为您在代码中的任何位置同时返回两个元素。

eg 例如

return(<div id="div1"></div><div id="div1"></div>)

It should be wrapped in a parent element. 应该将其包装在父元素中。 eg 例如

 return(<div id="parent"><div id="div1"></div><div id="div1"></div></div>)

More Detailed Explanation 更详细的解释

Your below jsx code get transformed 您下面的jsx代码得到了转换

 class App extends React.Component { render(){ return ( <div> <h1>Welcome to React</h1> </div> ); } } 

into this 进入这个

 _createClass(App, [{ key: 'render', value: function render() { return React.createElement( 'div', null, React.createElement( 'h1', null, 'Welcome to React' ) ); } }]); 

But if you do this 但是如果你这样做

 class App extends React.Component { render(){ return ( <h1>Welcome to React</h1> <div>Hi</div> ); } } 

this gets converted into this(Just for illustration purpose, actually you will get error : Adjacent JSX elements must be wrapped in an enclosing tag ) 这将转换为this(仅出于说明目的,实际上您会得到error : Adjacent JSX elements must be wrapped in an enclosing tag

 _createClass(App, [{ key: 'render', value: function render() { return React.createElement( 'div', null, 'Hi' ); return React.createElement( 'h1', null, 'Welcome to React' ) } }]); 

In the above code you can see that you are trying to return twice from a method call, which is obviously wrong. 在上面的代码中,您可以看到您正在尝试从方法调用返回两次 ,这显然是错误的。

Edit- Latest changes in React 16 and own-wards: 编辑-React 16和自己的区域中的最新更改:

If you do not want to add extra div to wrap around and want to return more than on child components you can go with React.Fragments . 如果您不想添加额外的div来包装并且想要返回比子组件更多的东西,则可以使用React.Fragments

React.Fragments are little bit faster and has less memory usage (no need to create an extra DOM node, less cluttered DOM tree). React.Fragments更快一点,并且具有更少的内存使用量(无需创建额外的DOM节点,更少的DOM树)。

eg (In React 16.2.0) 例如(在React 16.2.0中)

 render() { return ( <> React fragments. <h2>A heading</h2> More React fragments. <h2>Another heading</h2> Even more React fragments. </> ); } 

or 要么

 render() { return ( <React.Fragments> React fragments. <h2>A heading</h2> More React fragments. <h2>Another heading</h2> Even more React fragments. <React.Fragments/> ); } 

or 要么

 render() { return [ "Some text.", <h2 key="heading-1">A heading</h2>, "More text.", <h2 key="heading-2">Another heading</h2>, "Even more text." ]; } 

#5楼

If you don't want to wrap it in another div as other answers have suggested, you can also wrap it in an array and it will work. 如果您不想像其他答案所建议的那样将其包装在另一个div中,也可以将其包装在一个数组中,它将起作用。

// Wrong!
return (  <Comp1 /><Comp2 />
)

It can be written as: 它可以写成:

// Correct!
return (  [<Comp1 />,<Comp2 />]
)

Please note that the above will generate a warning: Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of 'YourComponent'. 请注意,以上内容将产生警告: Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of 'YourComponent'. Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of 'YourComponent'.

This can be fixed by adding a key attribute to the components, if manually adding these add it like: 可以通过向组件添加key属性来解决此问题,如果手动添加,则可以像这样添加:

return (  [<Comp1 key="0" />,<Comp2 key="1" />]
)

Here is some more information on keys: Composition vs Inheritance 以下是有关键的更多信息: 组合与继承


#6楼

The problem 问题

Parse Error: Adjacent JSX elements must be wrapped in an enclosing tag 解析错误:相邻的JSX元素必须包装在一个封闭标签中

This means that you are trying to return multiple sibling JSX elements in an incorrect manner. 这意味着您试图以错误的方式返回多个同级JSX元素。 Remember that you are not writing HTML, but JSX! 请记住,您不是在编写HTML,而是在编写JSX! Your code is transpiled from JSX into JavaScript. 您的代码从JSX转换为JavaScript。 For example: 例如:

render() {return (<p>foo bar</p>);
}

will be transpiled into: 将被转换成:

render() {return React.createElement("p", null, "foo bar");
}

Unless you are new to programming in general, you already know that functions/methods (of any language) take any number of parameters but always only return one value. 除非您一般不熟悉编程,否则您已经知道(任何语言的)函数/方法采用任意数量的参数,但始终仅返回一个值。 Given that, you can probably see that a problem arises when trying to return multiple sibling components based on how createElement() works; 鉴于此,您可能会发现基于createElement()工作方式尝试返回多个同级组件时会出现问题。 it only takes parameters for one element and returns that. 它仅接受一个元素的参数并返回该参数。 Hence we cannot return multiple elements from one function call. 因此,我们不能从一个函数调用中返回多个元素。


So if you've ever wondered why this works... 因此,如果您曾经想知道为什么这行得通...

render() {return (<div><p>foo</p><p>bar</p><p>baz</p></div>);
}

but not this... 但这不是...

render() {return (<p>foo</p><p>bar</p><p>baz</p>);
}

it's because in the first snippet, both <p> -elements are part of children of the <div> -element. 这是因为在第一个代码段中,两个<p>元素都是<div> -element的children的一部分。 When they are part of children then we can express an unlimited number of sibling elements. 当他们是children一部分时,我们可以表达无限数量的同级元素。 Take a look how this would transpile: 看一看如何转换:

render() {return React.createElement("div",null,React.createElement("p", null, "foo"),React.createElement("p", null, "bar"),React.createElement("p", null, "baz"),);
}

Solutions 解决方案

Depending on which version of React you are running, you do have a few options to address this: 根据您所运行的React版本,您确实可以通过几种方法来解决此问题:

  • Use fragments (React v16.2+ only!) 使用片段(仅适用于v16.2 +!)

    As of React v16.2, React has support for Fragments which is a node-less component that returns its children directly. 从React v16.2开始,React支持FragmentsFragments是一个无节点组件,可以直接返回其子级。

    Returning the children in an array (see below) has some drawbacks: 返回数组中的子级(见下文)有一些缺点:

    • Children in an array must be separated by commas. 数组中的子项必须用逗号分隔。
    • Children in an array must have a key to prevent React's key warning. 数组中的子代必须具有密钥,以防止React发出密钥警告。
    • Strings must be wrapped in quotes. 字符串必须用引号引起来。

    These are eliminated from the use of fragments. 这些都从使用片段中消除。 Here's an example of children wrapped in a fragment: 这是包裹在片段中的孩子的示例:

     render() { return ( <> <ChildA /> <ChildB /> <ChildC /> </> ); } 

    which de-sugars into: 哪个糖变成:

     render() { return ( <React.Fragment> <ChildA /> <ChildB /> <ChildC /> </React.Fragment> ); } 

    Note that the first snippet requires Babel v7.0 or above. 请注意,第一个片段需要Babel v7.0或更高版本。


  • Return an array (React v16.0+ only!) 返回一个数组(仅适用于v16.0 +!)

    As of React v16, React Components can return arrays. 从React v16开始,React组件可以返回数组。 This is unlike earlier versions of React where you were forced to wrap all sibling components in a parent component. 这与React的早期版本不同,在早期版本中,您被迫将所有同级组件包装在父组件中。

    In other words, you can now do: 换句话说,您现在可以执行以下操作:

     render() { return [<p key={0}>foo</p>, <p key={1}>bar</p>]; } 

    this transpiles into: 转换为:

     return [React.createElement("p", {key: 0}, "foo"), React.createElement("p", {key: 1}, "bar")]; 

    Note that the above returns an array. 请注意,以上代码返回一个数组。 Arrays are valid React Elements since React version 16 and later. 从React版本16及更高版本开始,数组是有效的React Elements。 For earlier versions of React, arrays are not valid return objects! 对于早期版本的React,数组不是有效的返回对象!

    Also note that the following is invalid (you must return an array): 另请注意,以下内容无效 (您必须返回一个数组):

     render() { return (<p>foo</p> <p>bar</p>); } 

  • Wrap the elements in a parent element 将元素包装在父元素中

    The other solution involves creating a parent component which wraps the sibling components in its children . 另一种解决方案涉及创建一个父组件,该组件将兄弟组件包装在其children组件中。 This is by far the most common way to address this issue, and works in all versions of React. 到目前为止,这是解决此问题的最常用方法,并且适用于所有版本的React。

     render() { return ( <div> <h1>foo</h1> <h2>bar</h2> </div> ); } 

    Note: Take a look again at the top of this answer for more details and how this transpiles . 注意:再次查看此答案的顶部,以获取更多详细信息以及如何转换

解析错误:相邻的JSX元素必须包装在一个封闭标签中相关推荐

  1. html中内联元素排列对齐原理,html标签中的内联元素(行内元素)详解

    html内联元素,也叫行内元素,相邻的多个内联元素是水平横向排列显示在同一行,其宽度随内容的变化而变化,在同一行显示多个内容,就可以使用内联元素来实现,这样就不需要将块级元素设置为浮动或绝对定位也能在 ...

  2. 前端开发 html第二课 自结束标签 注释 标签中的属性 文档声明 进制 字符编码 文档使用 VScode 实体 meta标签 语义化标签 块元素和行内元素 布局标签

    1 自结束标签 标签一般成对出现,但是也存在一些自结束标签 如: 多"/"和没有"/"区别不大 2 注释 注释的作用: 注释中的内容会被浏览器忽略,不会在网页中 ...

  3. 火狐浏览器 xml 解析错误:文档元素后存有无效内容_五分钟了解浏览器工作原理...

    作者简介: 李中凯 八年多工作经验 前端负责人, 擅长JavaScript/Vue. 掘金文章专栏:KaysonLi 的个人主页 - 专栏 - 掘金 Web 浏览器无疑是用户访问互联网最常见的入口.浏 ...

  4. XML 解析错误:找不到根元素

    现象: 使用ajax通信请求数据,浏览器控制台报"XML 解析错误:找不到根元素"错误 原因: 原因是后台数据返回值为null. 具体原因需分析确认,比如 ·后台响应方法为priv ...

  5. 网页添加飘动窗口(图片链接)+ IE8下js解析错误

    需求:在网站首页添加一个四处浮动的窗口(实际是一个图片,单击是一个地址链接). 1.网页上找到的一段javascript代码,写成了js文件. 1 var Rimifon = { 2 "Ad ...

  6. 关于vivo 8.0和miui新系统android studio调试出现“包解析错误”的bug的解决办法

    最近在工作中遇到了调试的时候将app安装到vivo 手机上,出现了包解析错误的问题.一般来说这种问题只会出现在手机版本 小于 app所要求的最低版本的手机上.但是此vivo手机的版本是8.0,很显然不 ...

  7. IIS 7.5 解析错误 命令执行漏洞解决方案

    这篇文章主要介绍了IIS 7.5 解析错误 命令执行漏洞解决方案,需要的朋友可以参考下 一.漏洞介绍 漏洞影响 IIS7 及IIS7.5 在使FastCGI方式调用php时,在php.ini里设置 c ...

  8. XML 解析错误:XML 或文本声明不在实体的开头位置,有效的解决方法

    2019独角兽企业重金招聘Python工程师标准>>> 昨天在测试APP接口返回XML数据的时候( http://my.oschina.net/woshixiaomayi/blog/ ...

  9. 窗口分析函数_14_生成相邻下一个元素

    生成相邻下一个元素 需求描述 需求:将EMP表里的部门编号为20的SAL字段按照由高到低排序取相邻的下一个SAL. 解决方法:通过lag OVER()来完成. 注: 数据库数据集SQL脚本详见如下链接 ...

最新文章

  1. 人工智能领域的经典著作!
  2. SQL SERVER 2008自动备份维护计划
  3. Facebook:正变为下一个微信?
  4. int数组,找小于右边所有数,大于左边所有数的数
  5. C++阶段01笔记04【程序流程结构(选择结构、循环结构、跳转语句)】
  6. 【解决】insert 语句无效果,在查询中正常运行问题
  7. “前”方有坑,绕道而行(一)-- H5 CSS
  8. linux man 后面的数字,Linux man命令的使用方法(以及后面数字的含义)
  9. ios加载本地html懒加载图片方案,IOS开发中加载大量网络图片优化方法
  10. 安装IPython攻略
  11. tomcat内存溢出全记录
  12. Markdown使用手册
  13. python 断言方法_Python3断言
  14. java 如何将base64 转成图片并保存,返回地址入库
  15. fullcalendar 日历改造
  16. Redis批量删除Key的三种方式(linux和windows环境下都有)
  17. Oracle EBS MTL_SUPPLY作用
  18. boss直聘python_爬Boss直聘,分析2019下半年Python工作现状
  19. 【P07】DIY推荐:OPA604高电压耳放
  20. Android第三方流式布局FlowLayout简单实用(搜索历史记录)

热门文章

  1. Android开发之大位图压缩水印处理
  2. 解决编译不通过Could not find support-compat.aar (com.android.support:support-compat:26.0.0).
  3. 解决Android Stadio 导入Android 项目,没有可运行的Module
  4. compileReleaseJavaWithJavac
  5. 在Eclipse中关联Android Private Libraries中文件的源代码
  6. uniapp处理IOS底部横条安全区域
  7. redis setnx实现分布式锁
  8. 用EC5/EC6自定义class的区别及用法 -- Phaser3网页游戏框架
  9. SpringMVC中Controller如何将数据返回
  10. C语言博客作业--数据类型