我能够将shouldForwardProp指定哪些props应该转发给作为选项传递给的包装元素放在一起styled(),但我无法找到其用例的可理解示例。
这里的 prop forwarding 类似于在 React 中传递 props 吗?
为什么要防止某些props在使用时被转发到被包裹的元素styled()?
请原谅我的无知,或者如果我的问题不够清晰 - 我仍在学习 MUI 并试图将我的头脑围绕它。
我能够将shouldForwardProp指定哪些props应该转发给作为选项传递给的包装元素放在一起styled(),但我无法找到其用例的可理解示例。
这里的 prop forwarding 类似于在 React 中传递 props 吗?
为什么要防止某些props在使用时被转发到被包裹的元素styled()?
请原谅我的无知,或者如果我的问题不够清晰 - 我仍在学习 MUI 并试图将我的头脑围绕它。
如果您正在使用像div或这样的内置组件,span并且您希望允许用户通过一些props自定义样式。
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存在的原因,以防止样式props被传递并创建无效属性:
const MyComponent = styled('div', {
shouldForwardProp: (props) => props !== 'bgColor',
})(({ bgColor }) => ({
backgroundColor: bgColor,
}));