我试图设置我的React.js应用程序,以便它只呈现如果我设置的变量为真。

我的渲染函数是这样设置的:

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>
    )
  },

基本上,这里重要的部分是if(this.state.submitted==false)部分(我希望这些div元素在提交的变量被设置为false时显示出来)。

但是当运行这个时,我在问题中得到了错误:

解析错误:第38行:相邻的JSX元素必须被封装在一个外围标记中

这里的问题是什么?我该怎么做呢?


当前回答

很简单,我们可以使用父元素div来包装所有元素 或者我们可以使用高阶分量(HOC)的概念,即非常有用的 React js应用程序

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

或者另一种最好的方法是HOC,它非常简单,不太复杂 只需在你的项目中添加一个hoc.js文件,并简单地添加这些代码

const aux = (props) => props.children;
export default aux;

现在导入hoc.js文件到你想要使用的地方,而不是用div包装 元素,我们可以用hoc来包装。

import React, { Component } from 'react';
import Hoc from '../../../hoc';

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

其他回答

只需添加

<>
  // code ....
</>

我认为当试图在return语句中嵌套多个div时,也会出现复杂情况。您可能希望这样做,以确保您的组件呈现为块元素。

下面是一个使用多个div正确呈现两个组件的例子。

return (
  <div>
    <h1>Data Information</H1>
    <div>
      <Button type="primary">Create Data</Button>
    </div>
  </div>
)

导入视图并在视图中换行。在div包装不工作对我来说。

import { View } from 'react-native';
...
    render() {
      return (
        <View>
          <h1>foo</h1>
          <h2>bar</h2>
        </View>
      );
    }

React元素只能返回一个元素。您必须用另一个元素标记来包装两个标记。

我还可以看到你的渲染函数没有返回任何东西。这是你的组件应该看起来的样子:

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

还要注意,你不能在返回的元素中使用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 />
    }
},

如果你不包装你的组件,那么你可以按照下面提到的方法来编写它。

而不是:

return(
  <Comp1 />
  <Comp2 />
     );

你可以这样写:

return[(
 <Comp1 />
),
(
<Comp2 />
) ];