我有兩個幾乎相同的組件,組件 A:
const ClaimedLabel = ():React.Element => (
<div tw="">
<p tw="">Some Text here</p>
<div tw="">
<Icon src="./icon.png" />
</div>
</div>)
B組份:
const ClaimedLabelPDF = ():React.Element => (
<View tw="">
<Text tw="">Some Text here</p>
<View tw="">
<Icon src="./icon.png" />
</View>
</View>)
tw - 是我忽略的順風風格,以提高代碼可重復性。如您所見,這兩個組件相同但使用了不同的標簽,是否可以撰寫一個組件來重用它?我有一個使用 isPDF 標志的想法,將兩個組件合二為一并根據標志值回傳組件,但在這種情況下我仍然有重復項:
const ClaimedLabel = (isPDF: boolean): React.Element => isPDF ? <View>...</View> : <div....</div>
uj5u.com熱心網友回復:
您可以只創建對需要交換的元素型別的參考。
const ClaimedLabel = (isPDF: boolean): React.Element => {
const RView = isPdf ? View : 'div';
const RText = isPdf ? Text : 'p';
return (
<RView tw="">
<RText tw="">Some Text here</p>
<RView tw="">
<Icon src="./icon.png" />
</RView>
</RView>
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/523610.html