[英]How to use props within the same component?
我正在尋找一個充滿推文的組件。
我正在創建一個名為“tweets”的數組,我想在 return() 中訪問該數組。 我知道映射,但有沒有辦法只在頁面上顯示一個? 我認為它會像 {this.props.name} 或只是 {props.name} 但它不會向頁面呈現任何內容。
如何在同一組件中將道具引用到我的頁面?
推文.js
import React from 'react';
const Tweets = (props) => {
const tweets = [
{name: 'Name 1',
tweet:'This is a tweet!'},
{name:'Name 2',
tweet:'This is another tweet'},
{name:'Name 3',
tweet:'This is yet another tweet!'},
]
return (
<section>
<h1>{this.props.name}</h1>
</section>
)
}
export default Tweets;
您的推文位於組件本身內部,它們不是來自道具。 因此,您可以使用以下方式訪問單個值:
{tweets[0].name}
如果要全部顯示,可以執行以下操作:
return (
<section>
{
tweets.map(({name, tweet}) => (
<div>
<h1>{name}</h1>
<p>{tweet}</p>
</div>
))
}
</section>
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.