Vin*_*e N 52 reactjs material-ui
我能够将shouldForwardProp指定哪些道具应该转发到作为选项传递的包装元素放在一起styled(),但我无法找到其用例的可理解的示例。
这里的 prop 转发类似于在 React 中传递 props 吗?
为什么在使用时要阻止某些道具被转发到包装元素styled()?
请原谅我的无知或者我的问题不够清晰——我仍在学习 MUI 并试图理解它。
Nea*_*arl 85
div如果您正在使用诸如或 之类的内置组件,span并且您希望允许用户通过某些道具自定义样式。
const MyComponent = styled('div')(({ bgColor }) => ({
backgroundColor: bgColor,
}));
Run Code Online (Sandbox Code Playgroud)
当你像这样使用它时:
<MyComponent bgColor='red'>
Run Code Online (Sandbox Code Playgroud)
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.
Run Code Online (Sandbox Code Playgroud)
这就是shouldForwardProp存在的原因,以防止样式道具被传递并创建无效属性:
const MyComponent = styled('div', {
shouldForwardProp: (props) => props !== 'bgColor',
})(({ bgColor }) => ({
backgroundColor: bgColor,
}));
Run Code Online (Sandbox Code Playgroud)
mar*_*424 14
@NearHuscarl 已经给出了很好的答案!
如果您使用 TypeScript,我会使用实用程序函数,因此我总是正确输入 prop 名称:
export const shouldForwardProp = <CustomProps extends Record<string, unknown>>(
props: Array<keyof CustomProps>,
prop: PropertyKey,
): boolean => !props.includes(prop as string);
const MyComponent = styled('div', {
shouldForwardProp: (prop) => shouldForwardProp<MyComponentProps>(['isDisabled', 'bgColor'], prop),
})<MyComponentProps>(({ theme, isDisabled, size, bgColor }) => ({
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23198 次 |
| 最近记录: |