【问题标题】:What is the purpose of shouldForwardProp option in styled()?styled() 中 shouldForwardProp 选项的作用是什么?
【发布时间】:2021-10-26 21:47:45
【问题描述】:

我能够将 shouldForwardProp 指定哪些道具应该转发给作为选项传递给 styled() 的包装元素放在一起,但我很难找到一个易于理解的用例示例。

这里的 prop 转发类似于在 React 中传递 props 吗?

在使用styled() 时,为什么要阻止某些道具被转发到被包装的元素?

请原谅我的无知,或者如果我的问题不够清晰 - 我仍在学习 MUI 并试图围绕它来解决问题。

【问题讨论】:

    标签: reactjs material-ui


    【解决方案1】:

    如果您使用像 divspan 这样的内置组件,并且您希望允许用户通过一些道具自定义样式。

    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,
    }));
    

    【讨论】:

    • 与使用简单的 className @NearHuscarl 相比有什么好处?
    • 我希望他们在文档中如此清晰地解释它?谢谢。
    猜你喜欢
    • 2014-11-01
    • 2021-11-19
    • 2019-10-16
    • 2018-12-01
    • 2014-03-12
    • 2018-06-17
    • 2023-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多