[英]React PropTypes - OR
對於這段代碼:
const FirstComponentPropTypes = {
foo: PropTypes.any,
};
const SecondComponentPropTypes = {
bar: PropTypes.any,
};
...
function MyComponent({ foo, bar }) {
if (foo) {
return <FirstComponent foo={foo} />;
} else if (bar) {
return <SecondComponent bar={bar} />;
}
throw new Error("Invalid props.");
}
為了設置MyComponent
的propTypes
,是否可以執行以下操作:
MyComponent.propTypes = FirstComponentPropTypes | SecondComponentPropTypes;
?
正如您所指出的:
MyComponent 是一個“通用”組件,如果存在 foo 則呈現 A,如果存在 bar 則呈現 B。
它的定義是function MyComponent({ foo, bar }) {... }
為了避免復雜的解決方案,我建議您將條件邏輯移到MyComponent
之外。 這樣,您將需要 MyComponent 的單個 propType 定義,而無需復制其他兩個組件的 propType 定義。 您的組件將檢查的類型是element
,這是所有 React 元素共享的通用類型。
MyComponent.propTypes = {
elementToRender: PropTypes.element
};
所以你需要調整你的組件定義:
function MyComponent({ elementToRender }) { ... }
以及它的使用方式:
const getComponentToRender = (foo, bar) => {
if (foo) {
return <FirstComponent foo={foo} />;
} else if (bar) {
return <SecondComponent bar={bar} />;
} else {
return null;
}
}
const element = getComponentToRender(foo, bar)
你的 jsx:
{!element && <YourErrorComponent />}
{element && <MyComponent elementToRender={element} />}
如果需要,您始終可以在不使用常量或變量的情況下將條件邏輯放入組件中。
這種方法的最大好處是您的MyComponent
不需要了解您FirstComponent
或SecondComponent
類型的任何信息。 並且您始終可以選擇使用另一個組件傳遞給MyComponent
而無需更改它。
此外,您在定義類型的代碼中只有一個點,並且它們之間沒有任何依賴關系。
此外,您不會在某一點獲得道具,然后在遠離它的條件下使用它們。
為了讓您的代碼易於閱讀,我建議您避免對元素使用特定的屬性。 使用props.children
代替:
{element && <MyComponent>{element}</MyComponent>}
這是一種更React 式(自然)的方式來顯示另一個組件內的組件: children
props 就是為此目的而存在的。
此外,您可以(再次)在 MyComponent 中放置一個回退邏輯:
function MyComponent({ children }) {
if (children) {
return <div className="container">{children}</div>
}
return <p>children is missing</>
}
我假設你的意思是|
比如你想把這兩個集合結合起來? 您可以將這兩個對象與 Object.assign() 之類的東西合並:
const FirstComponentPropTypes = {
foo: PropTypes.any,
};
const SecondComponentPropTypes = {
bar: PropTypes.any,
};
function MyComponent({ foo, bar }) { ... }
MyComponent.propTypes = Object.assign({}, SecondComponentPropTypes, FirstComponentProptypes);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.