簡體   English   中英

(React) 僅在滿足條件時如何渲染組件

[英](React) How to render component only if condition is met

我試圖僅在滿足條件時呈現子組件,但無論我嘗試什么,都沒有真正起作用。 我收到各種錯誤。

我的應用程序是一個商店,其中包含一個可供客戶使用的水果列表。 我只想渲染選擇到他們籃子里的項目。 這就是 Facture.js 正在嘗試做的事情。 我正在嘗試檢查列表中count > 0的每個水果的數量,而當它為 0 時什么都沒有。

現在,它正在渲染列表中的所有內容,即使我不想要它們——我知道在這個實際代碼中沒有條件,所以它返回所有內容。

它不應該像 if 塊一樣簡單嗎?


如果有幫助,這是我的完整代碼結構:

應用程序.js

import Client from "./Client";

state = { fruits : [{name: "Apple", price: "3", count: 2}, 
                    {name: "Orange", price: "2", count: 0}] }

render() { <Client fruits={this.state.fruits}/> }

// I tried this : {this.props.fruits.count > 0 ? <Factures fruits={this.props.fruits} /> : null} but it returns nothing.

客戶端.js

import Factures from "./Factures";
render() { <Factures fruits={this.props.fruits}/> }

Factures.js

import Facture from "./Facture";
render() {
      return this.props.fruits.map(fruit => <Facture key={fruit.nom} fruit={fruit} /> );
}

Facture.js

class Facture extends React.Component {
   render() {
      return (
         <li className='list-group-item d-flex justify-content-between small'>
            <div className=''>{this.props.fruit.name}</div>
            <div className=''>{'x' + this.props.fruit.count}</div>
         </li>
      );
   }
}

export default Facture;

您可以通過以下幾種方式做到這一點:

選項 A:過濾水果數組,然后將其作為道具傳遞給Client

這個方法意味着你不需要在你的子組件中設置條件,因為你只會傳遞你想要渲染為道具的水果。

// only keep fruits if fruit.count > 0
render() { <Client fruits={this.state.fruits.filter(fruit => fruit.count > 0}/> }

選項 B: Facture組件中的條件渲染

此方法將檢查每個水果的數量,並且只渲染水果的數量fruit.count > 0

class Facture extends React.Component {
  render() {
    // if `fruit.count > 0`, render. otherwise, null
    return this.props.fruit.count > 0 ? (
      <li className="list-group-item d-flex justify-content-between small">
        <div className="">{this.props.fruit.name}</div>
        <div className="">{"x" + this.props.fruit.count}</div>
      </li>
    ) : null;
  }
}

export default Facture;
class Facture extends React.Component {
   constructor(props) {
     super(props);
   }

   render() {
      return (
        {this.props.fruit.count > 0 && 
         <li className='list-group-item d-flex justify-content-between small'>
            <div className=''>{this.props.fruit.name}</div>
            <div className=''>{'x' + this.props.fruit.count}</div>
         </li>
        }
      );
   }
}

export default Facture;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM