[英]Render React Component Depending on its Type
我想知道在 React 中是否有一種方法可以根據組件的類型有條件地渲染組件。 根據文檔,您可以通過以下方式定義組件的道具類型:
MyComponent.propTypes = {
description: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]),
};
有沒有辦法使用框架檢查類型並根據接收到的道具數據是string
還是array
來以不同的方式呈現組件?
我知道我可以使用原始 JS 來確定這一點,方法是使用type of
或檢查數據數組的屬性。
if (typeof description === "string") { /* render string component */ }
else { /* render array component */ }
我想知道 React 是否有內置的、更強大的方法來執行此操作。
我想知道 React 是否有內置的、更強大的方法來執行此操作。
description
是一個聯合道具類型。
因此,您需要通過使用render props來實現渲染邏輯。
const StringDescription = (props) => {...}
const ArrayDescription = (props) => {...}
function renderDescription(description) { // rendering logic / strategy
switch(typeof description) {
case 'string':
return <StringDescription />;
default:
return <ArrayDescription />;
}
}
<Description
description={description}
render={renderDescription} // render prop
/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.