我正在将现有的应用程序转换为ReactJS。我在ReactJS中发现了很难做到的事情。以下是我想做的事情
render () {
return (<div id="container">
<div className="shared">shared content here</div>
<div className="shared">shared content here</div>
<div className="shared">shared content here</div>
{featureAEnabled ?
(<div className="featureA">featureA enabled content</div>
<div className="featureA">featureA enabled content</div>) :
(<div className="old">featureA disabled content</div>
<div className="old">featureA disabled content</div>)
</div>);
}
问题是你不能在React中返回多个元素,你必须总是返回一个元素。
我目前的解决方案涉及
代码:
render() {
return (<div id="container">
<div className="shared">shared content here</div>
<div className="shared">shared content here</div>
<div className="shared">shared content here</div>
{featureAEnabled && <div className="featureA">featureA enabled content</div>}
{featureAEnabled && <div className="featureA">featureA enabled content</div>}
{!featureAEnabled && <div className="old">featureA disabled content</div>}
{!featureAEnabled && <div className="old">featureA disabled content</div>}
</div>);
}
有没有办法允许基于条件的代码块并在我的第一个代码片段中呈现多个元素?
答案 0 :(得分:1)
理想情况下,您应该尝试分离“featureAnabled&#39;和&#39; featureADisabled&#39;单独组件中的元素,然后呈现它们。
这样做的另一种方法就是让你的功能成为可能的&#39;和&#39; featureADisabled&#39;数组中的元素并返回它。如下所示:
render() {
let renderFeatureA = [
<div >featureA enabled content</div>,
<div >featureA enabled content</div>
];
let disableFeatureA = [
<div >featureA disabled content</div>,
<div >featureA disabled content</div>
];
let renderItems = featureAEnabled ? renderFeatureA : disableFeatureA;
return (
<div id="container">
<div >shared content here</div>
<div >shared content here</div>
<div >shared content here</div>
{renderItems}
</div>
)
};
答案 1 :(得分:0)
这样做的一种方法是在渲染中切换一个类。
let featureEnabledClasses = 'hidden';
if (myCondition === true) {
featureEnabledClasses = '';
}
然后你可以提供
<div className={featureEnabledClasses}>featureA enabled content</div>