[英]Conditional rendering of component
我僅在asset.id === collection.masterAssetId
時才嘗試渲染組件。 如果是這種情況,應該會出現一個星形圖標。 我正在使用getMasterId
function 來檢查這種情況。 有誰知道這里的錯誤是什么?
錯誤:
Parsing error: Unexpected token
70 |
71 | {
> 72 | if(asset.id === this.getMasterId(asset.id)){
| ^
73 | <FaStar />
74 | }}
應用程序.js
import React from 'react';
import './App.css';
import {collections} from "./data.js"
import {assets} from "./data.js"
import {FontAwesome, FaStar} from "react-icons/fa"
class App extends React.Component {
constructor() {
super()
this.state = {
collectionsarr: collections,
assetsarr: assets,
clickedassets: []
}
}
getMasterId(assetnr){
const assetnum = this.state.collectionsarr.find(element => element.masterAssetId === assetnr).masterAssetId
return assetnum
}
render(){
return (
<div className="App">
<h1>Sitecore coding challenge</h1>
<div className="left">
{this.state.collectionsarr.map(element =>
<div key={element.id}>
<p onClick={()=>this.handleAssetsClick(element.id)}>{element.name}</p>
<img src={this.getAssetPath(element.masterAssetId)} alt="pic"/>
<br></br>
</div>
)}
</div>
<div className="right">
{this.state.clickedassets.map(asset =>
<div key={asset.id}>
<img src={require(`./${asset.path}`)} alt="pic"/>
<p>{asset.name}</p>
<p>{asset.id}</p>
<button onClick={() => this.makeMaster(asset.id)}>Make master!</button>
<p>icon "this is the master</p>
{
if(asset.id === this.getMasterId(asset.id)){
<FaStar />
}}
<br></br>
</div>
)}
</div>
</div>
)
}
}
您不能在 return 語句的內聯代碼中使用語句。 您只能使用表達式。
if 語句是一個語句,因此您應該將其替換為表達式,例如三元運算符x? y: z
x? y: z
或條件運算符&&
:
// ternary
asset.id === this.getMasterId(asset.id) ? <FaStar /> : null
或者:
// conditional and
asset.id === this.getMasterId(asset.id) && <FaStar />
React 有一些關於條件渲染的優秀文檔。
使用條件和&&
時要小心,好像第一個參數是數字0
(例如, list.length && <Component />
),那么您最終將呈現0
而不是什么都沒有。
在這些情況下,最好轉換為 Boolean:
Boolean(list.length) && <Component />
或者:
!!list.length && <Component />
看看這是否有效
(asset.id === this.getMasterId(asset.id))? <FaStar />: <></>;
在渲染 function 的返回代碼中,您只能使用表達式(等號右側允許使用的東西)。 if
是一個語句,所以它是不允許的。 不起作用的示例:
const a = if(asset.id === this.getMasterId(asset.id)) return <FaStar />
但是,允許使用三元表達式。 然后看起來像這樣:
const a = asset.id === this.getMasterId(asset.id) ? <FaStar /> : null
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.