簡體   English   中英

如何在 React 中訪問兒童道具

[英]how to access children props in React

真的很抱歉,我知道這已經發布過,但我只是不明白答案與我的問題有什么關系。 我對反應很陌生,需要比我能找到的更多的幫助。

我的應用項目有這樣的評論;

const restaurantData = [
  {
    id: 1,
    restaurantName: "Restaurant 1",
    address: "4, Dolphin Way, Swansea SA10 5BZ",
    lat: 48.8737815,
    long: 2.3501649,
    ratings: [{ ratingID: 1, stars: 2, comment: "Terrible service, Yikes!" }],
  },
];

而且我已經訪問了這樣的數據沒有問題;

function RestaurantItem({ restaurant }) {
  return (
    <div className="restaurantItem" id={restaurant.id}>
      <h2 className="AsideHeader">{restaurant.restaurantName}</h2>
      <p className="AsideAddress">{restaurant.address} </p>
    </div>
  );
}

我基本上想通過這樣做來專門訪問評論數據;

<div>
  <p>{restaurant.ratings.stars} STAR : </p> {restaurant.ratings.comment}
</div>

但我沒有任何運氣。 有人可以解釋我做錯了什么以及如何解決嗎? 或者甚至我會稱之為什么來查找解決方案?

謝謝你 !

由於 restaurant.ratings 是一個列表,因此您不能像字符串一樣顯示它。

你可以像這樣顯示它們:

<div>
  {restaurant.ratings.map((rating, index) => (
    <p key={"rating-" + rating.ratingID}>
      {rating.stars + " STAR : " + reating.comment}
    </p>
  ))}
</div>

列表的 map 方法迭代每個元素,並將每個元素作為 JSX 元素作為匿名方法“描述”返回。

ratings是一個數組,因此您不能以ratings.starsratings.comment的形式訪問數據。

一種方法是使用map迭代評級並顯示該特定餐廳的所有評級。

<div>
  {restaurant.ratings.map((rating) => (
    <p key={rating.ratingID}>{`${rating.stars} STAR: ${rating.comment}`}</p>
  ))}
</div>

在您的const restaurantData中, ratings是一個數組。 如果只有 1 個評分,則刪除數組: ratings: { ratingID: 1, stars: 2, comment: "Terrible service, Yikes!" } ratings: { ratingID: 1, stars: 2, comment: "Terrible service, Yikes!" }

如果會有多個評級,則使用.map循環每個評級。

  {restaurant.ratings.map((rating) => (
    <div key={rating.ratingID}>
      <p>{rating.stars} STAR : </p> {rating.comment}
    </div>
  ))}

您在數組上調用道具,但您需要在數組元素上調用道具。

如果 ratings 屬性總是有一個元素,那么你可以這樣寫,但這將是一個拐杖

function RestaurantItem({ restaurant }) {
  return (
    <div className="restaurantItem" id={restaurant.id}>
      <h2 className="AsideHeader">{restaurant.restaurantName}</h2>
      <p className="AsideAddress">{restaurant.address} </p>
    </div>
    <div>
    <p>{restaurant.ratings[0].stars} STAR : </p> {restaurant.ratings[0].comment}
</div>
  );
}

@lich 報告正確,要使用數組,您必須使用 map 方法

使用 reactjs 列表看這里

js arrays

暫無
暫無

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

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