對于此代碼:
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.");
}
為了設定propTypesof MyComponent,是否可以執行以下操作:
MyComponent.propTypes = FirstComponentPropTypes | SecondComponentPropTypes;
?
uj5u.com熱心網友回復:
正如你所指出的:
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-ish (自然) 的方式來顯示另一個組件中的組件:childrenprops 的存在就是為了這個目的。
此外,您可以(再次)在 MyComponent 中放置一個后備邏輯:
function MyComponent({ children }) {
if (children) {
return <div className="container">{children}</div>
}
return <p>children is missing</>
}
uj5u.com熱心網友回復:
我假設您的意思|是您想合并兩組?您可以將這兩個物件與 Object.assign() 之類的東西合并:
const FirstComponentPropTypes = {
foo: PropTypes.any,
};
const SecondComponentPropTypes = {
bar: PropTypes.any,
};
function MyComponent({ foo, bar }) { ... }
MyComponent.propTypes = Object.assign({}, SecondComponentPropTypes, FirstComponentProptypes);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/443813.html
標籤:javascript 反应 反应式 反应属性类型
上一篇:如何處理復選框動作-反應原生?
