我在React中有一个If组件,非常简单:
'use strict';
var React = require('react');
module.exports = React.createClass({
render: function () {
if (this.props.condition) {
return this.props.children;
}
return false;
}
});我可以这样说:
<If condition={someLogic}>
<div>Hi there</div>
</If>问题是,如果If组件中有多个标记:
<If condition={someLogic}>
<div>Container 1</div>
<div>Container 2</div>
</If>这给了我一个错误:
未知错误:不变冲突: exports.render():必须返回有效的ReactComponent。您可能已返回未定义的数组或其他无效对象。
这里,this.props.condition是一个ReactElement数组。
问题:如何连接一个ReactElement数组并只返回一个?
注意:我意识到我可以将这两个divs放在一个包装器中,但是为了这个示例(以及我的实际问题),假设您不能这样做,您必须返回多个标记。
发布于 2015-07-13 17:56:13
React不支持从呈现中返回多个组件。方法必须返回一个元素-您可以看到问题https://github.com/facebook/react/issues/2127和https://github.com/facebook/react/issues/2191。
解决方案是用一些元素包装props.children,例如
var If = React.createClass({
render: function () {
if (this.props.condition) {
return <div>{this.props.children}</div>;
}
return false;
}
});发布于 2015-08-05 12:28:51
另一个解决你想要做的事情(而不是你想要的)的解决方案是使用一个功能if。
function test (condition, result, alternative) {
if (condition) {
return result;
} else {
return alternative;
}
}
<div>
{test(a === b, <b>Equal</b>)}
</div>这相当于三元操作符{a === b ? <b>Equal</b> : null}。
https://stackoverflow.com/questions/31388004
复制相似问题