今天的練習是要在 Card.jsx 裡面加入 id
這個 pros,而且要是用 Paragraph tag <p>
。
目前 Card.jsx 的樣子,我已經現在挑戰指定的地方加好 tag:
import React from "react";
import Avatar from "./Avatar";
import Detail from "./Detail";
function Card(props) {
return (
<div className="card">
<div className="top">
<p></p>
<h2 className="name">{props.name}</h2>
<Avatar img={props.img} />
</div>
<div className="bottom">
<Detail detailInfo={props.tel} />
<Detail detailInfo={props.email} />
</div>
</div>
);
}
export default Card;
依照目前學到的,用 props.name
可以叫出名字,那改成 key 應該也可以:
<p>{props.key}</p>
這時就會出現 Warning,而且 Web 沒有顯示 id 內容:
Warning: Card: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://fb.me/react-special-props)
Google 找到了這個:
Most props on a JSX element are passed on to the component, however, there are two special props (ref and key) which are used by React, and are thus not forwarded to the component.
所以我回去 DevTool 看,也會發現 Object 裡沒有 id。先回去 App.jsx 加個 id
property 看看:
function createCard(contact){
return <Card
name={contact.name}
img={contact.imgURL}
tel={contact.phone}
email={contact.email}
key={contact.id}
id={contact.id}
// 雖然跟key重複,但還是要另外列一個id才能出現在Object裡面。
/>
}
OK~ 一加上去就發現 HTML 出現 id,以及 DevTools 顯示 Object 出現 id!完成~