![](/img/trans.png)
[英]React: 'this.state' of parent component is undefined inside a child component function
[英]React: Pass image from this.state in parent component to child component
我有一個圖像,我已經導入到這樣的 React 類組件中:
import Hat3 from './assets/hat3/hat3.png';
要在此組件中顯示此圖像,我可以執行以下操作:
<img src={hat3} />
我有一個名為 FeaturedItem 的子組件,如下所示:
<FeaturedItem hat={this.state.hat3}/>
我想通過 prop hat
將hat3
圖像傳遞給 FeaturedItem 組件。 如何將hat3
圖像存儲在 state 中,以便我可以將其傳遞給功能性 FeaturedItem 組件?
我嘗試了以下方法:
constructor(props) {
super(props);
this.state = {
// Doesn't work
hat3: {hat3}
// Doesn't work
hat3: ${hat3}
// Doesn't work
hat3: `${hat3}`
};
}
將此圖像存儲在狀態以便我可以通過道具將其傳遞給子組件並將其顯示在子組件中的正確方法是什么?
試試下面的代碼
this.state = {
hat3: Hat3
};
如果這不起作用,請您分享您遇到的錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.