gpt4 book ai didi

javascript - 连接 ReactElements 进行渲染

转载 作者:行者123 更新时间:2023-11-28 00:05:23 24 4
gpt4 key购买 nike

我在 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>

这给了我一个错误:

Uncaught Error: Invariant Violation: exports.render(): A valid ReactComponent must be returned. You may have returned undefined, an array or some other invalid object.

这里 this.props.condition 是一个 ReactElement 数组。

问题:如何连接一组 ReactElement 并仅返回一个?

注意:我意识到我可以将这两个 div 放入一个包装器中,但为了这个示例(以及我的实际问题),我们可以这样说你不能这样做,并且你必须返回多个标签

最佳答案

React 不支持从渲染返回多个组件。渲染方法必须返回一个元素 - 您可以看到问题 https://github.com/facebook/react/issues/2127https://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;
}
});

关于javascript - 连接 ReactElements 进行渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31388004/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com