首页 > 解决方案 > 组件的条件渲染

问题描述

我试图仅在asset.id === collection.masterAssetId. 如果是这种情况,应该会出现一个星形图标。我正在使用该getMasterId功能来检查这种情况。有谁知道这里的错误是什么?


错误:

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>
        )
  }
}

标签: javascriptreactjs

解决方案


您使用的语法错误,请将其更改为

 { asset.id === this.getMasterId(asset.id) && <FaStar /> }

在此处阅读有关条件渲染的更多信息


推荐阅读