我能夠將shouldForwardProp指定哪些道具應該轉發給作為選項傳遞給的包裝元素styled(),但我無法找到其用例的可理解示例。
這里的 prop forwarding 類似于在 React 中傳遞 props 嗎?
為什么要防止某些道具在使用時被轉發到被包裹的元素styled()?
請原諒我的無知,或者如果我的問題不夠清晰 - 我仍在學習 MUI 并試圖將我的頭腦圍繞它。
uj5u.com熱心網友回復:
如果您使用內置組件,例如div或span并且您希望允許用戶通過某些道具自定義樣式。
const MyComponent = styled('div')(({ bgColor }) => ({
backgroundColor: bgColor,
}));
當你像這樣使用它時:
<MyComponent bgColor='red'>
prop 作為屬性傳遞給 DOM 樹中的真實元素:

而 react 會抱怨,比如:
Warning: React does not recognize the `bgColor` prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase `bgcolor` instead. If you accidentally passed it from a parent component, remove it from the DOM element.
這就是shouldForwardProp存在的原因,以防止樣式道具被傳遞并創建無效屬性:
const MyComponent = styled('div', {
shouldForwardProp: (props) => props !== 'bgColor',
})(({ bgColor }) => ({
backgroundColor: bgColor,
}));
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/338061.html
