[英]JSX: Conditional statement within a map
我試圖了解如何在 JSX 中合並條件語句。 我有一個要映射到 select 框的對象數組。 我想排除在 indicator.name 中包含 substring“閾值”的項目。
所以我不能使用三元運算符,因為沒有“或”項。 但我無法弄清楚如何在此 map 中包含 if 語句。無論我嘗試什么,都會出現錯誤。
<select defaultValue={defaultValue} onChange={e => setIndicator(e.currentTarget.value)} disabled={loading} > <option key='' value=''> Select </option> {indicatorList.map(indicator => ( <option key={indicator.name} value={indicator.name}> {indicator.label} </option> ))} </select>
你可以過濾然后 map:
<select
defaultValue={defaultValue}
onChange={e => setIndicator(e.currentTarget.value)}
disabled={loading}
>
<option key='' value=''>
Select
</option>
{indicatorList.filter(indicator=>indicator.name.includes('threshold')).map(indicator => (
<option key={indicator.name} value={indicator.name}>
{indicator.label}
</option>
))}
</select>
或返回 null:
<select
defaultValue={defaultValue}
onChange={e => setIndicator(e.currentTarget.value)}
disabled={loading}
>
<option key='' value=''>
Select
</option>
{indicatorList.map(indicator => (
indicator.name.includes('threshold')?<option key={indicator.name} value={indicator.name}>:nul
{indicator.label}
</option>
))}
</select>
我建議使用 filter 方法來過濾掉“閾值”。 這將返回您期望在 JSX 中擁有的數組
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.