条件渲染反应JS(一个条件内状态)
问题描述:
其实我试图隐藏和显示在一些HTML元素反应。 我创建了一个雇员表格,其中我们有多个分区,例如个人信息,联系信息等...... 我在表单中创建了下一个和上一个按钮,以表格形式显示和隐藏其他分区 有一个分区,其中我们有教育细节来填补,所以我选择保留加号和减号按钮来添加使用条件的教育细节。条件渲染反应JS(一个条件内状态)
But finally, my problem is like i have complex conditions on **render** function:
{someCondition && <div>
{anotherCondition && <div></div>}
</div>}
But, i'm getting: *Adjacent JSX elements must be wrapped in an enclosing tag error*. So, what i'm supposed to do?
答
从你给的代码,我相信你需要这样一个封闭标签:
//div wraps everything else so the component can render.
<div>
{someCondition && <div>
{anotherCondition && <div></div>
</div>}
</div>
答
你必须首先将它们包装在一个div。此外,你的语法看起来有点不对(你错过了关闭}
)。
{someCondition && (
<div>
{anotherCondition && <div></div>}
</div>
)}
+0
感谢您的更正,但上面的代码是不是我原来的代码,我刚刚给我的问题的例子.. ;-) –
答
你必须总是返回一个单个元素包围等。
由于有关条件的呈现,这里有一些小窍门你可以考虑:
A.简单的条件下,三元运算符是不够干净:
return condition ? <p>abc</p> : <p>def</p>
B.对清洁代码或创建渲染功能更复杂的if-else
renderButton =() => {
if (isLoading) { return false }
if (something) {
return <div></div>
} else {
return <div></div>
}
}
render() {
return (
<div>
{ this.renderButton }
</div>
)
}
C.与上面相同,但没有创造新的功能:
render() {
return (
<div>
{
(()=>{
if (something) {
return <div></div>
} else {
return <div></div>
}
})()
}
</div>
)
}
你的返回块的代码是什么样的? –
对不起兄弟,我不明白你的问题 –