你能在JSX中使用if语句吗?
var chartGraphContent =
<div className={"chartContent"}>
if(this.state.modalityGraph['nca'] > 0){
<div className={"chart-container"}>
<Chart
chartType="ColumnChart"
data = { this.state.modalityGraph?this.state.modalityGraph.chartData['units']:emptyDataRows }
options={chartOptions}
graph_id="modalitiesChart"
width="100%"
height="250px"
/>
</div>
}
</div>;
Run Code Online (Sandbox Code Playgroud)
像上面的东西?是否可以根据条件使用JSX?
当我们在 JSX 中返回一些东西时,我们可以这样写:
<ul>
{Array.from({ length: 9 }).map((e, i) => (
<li>{i}</li>
))}
</ul>
Run Code Online (Sandbox Code Playgroud)
或使用 IIFE:
<ul>
{(function () {
const result = [];
for (let i = 0; i < 9; i++) {
result.push(<li>{i}</li>);
}
return result;
})()}
</ul>
Run Code Online (Sandbox Code Playgroud)
示例:https : //codesandbox.io/s/busy-aryabhata-egv27
但是有没有可能写出类似的东西:
<ul>
{
const result = [];
for (let i = 0; i < 9; i++) {
result.push(<li>{i}</li>);
}
return result; // somehow "return" the array
}
</ul>
Run Code Online (Sandbox Code Playgroud)
也就是说,只需编写没有 IIFE 的纯代码,并且能够以某种方式返回我们创建的数组?