If-Else的ReactJS JSX语法
问题描述:
我有以下jsx代码,我试图将某些代码移出映射函数,但是jsx语法出错,我希望仅在有一些数据的情况下显示此块.
I have the following jsx code, I am trying to put some code out of the mapping function, but getting errors with the jsx syntax, I want this block displayed only if there is some data..
{this.props.someData ?
<div className="container">
<h3>Heading</h3>
<div className="block1">
<button>one</button>
<buttontwo</button>
</div>
this.props.someData.map((response, index) => {
return (
<div className="Block2">
<div key={index}>
<span>{response.number}</span>
</div>
</div>
</div>
);
}) : ''}
答
像这样写:
{this.props.someData ?
<div className="container">
<h3>Heading</h3>
<div className="block1">
<button>one</button>
<buttontwo</button>
</div>
{this.props.someData.map((response, index) => {
return (
<div className="Block2">
<div key={index}>
<span>{response.number}</span>
</div>
</div>
)})
}
</div>
: <div/>}
您正在做的错误:
要在html元素内呈现任何js代码,必须使用{}
,因为如果条件为true且在使用map
的条件下呈现JSX
,则呈现JSX
,因此将map
函数放在{}
内,它将工作.
To render any js code inside html elements, {}
is required, since you are rendering JSX
if the condition is true and inside that using map
so put map
function inside {}
, it will work.