我试图设置我的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中,你也可以把它包装在一个数组中,它会工作。
// Wrong!
return (
<Comp1 />
<Comp2 />
)
可以写成:
// Correct!
return (
[<Comp1 />,
<Comp2 />]
)
警告:数组或迭代器中的每个子元素都应该有一个唯一的“key”道具。检查“YourComponent”的渲染方法。
这可以通过为组件添加一个key属性来修复,如果手动添加这些属性,则如下所示:
return (
[<Comp1 key="0" />,
<Comp2 key="1" />]
)
这里有更多关于键的信息:组合与继承
很简单,我们可以使用父元素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>
);
}
对于Rect-Native开发者。我在FlatList中renderingItem时遇到了这个错误。我有两个文本组件。我是这样使用它们的
renderItem = { ({item}) =>
<Text style = {styles.item}>{item.key}</Text>
<Text style = {styles.item}>{item.user}</Text>
}
但是在我把这两个内部视图组件后,它为我工作。
renderItem = { ({item}) =>
<View style={styles.flatview}>
<Text style = {styles.item}>{item.key}</Text>
<Text style = {styles.item}>{item.user}</Text>
</View>
}
您可能正在使用其他组件,但将它们放入View可能对您有用。