将 sx prop 添加到自定义组件

Mat*_*ong 7 javascript reactjs material-ui

我正在使用 MUI v5 和 Gatsby Image。我希望在整个应用程序中保持样式语法的一致性,因此我尝试将sxprop 添加到GatsbyImage.

这是我尝试过的:

<Box
  component={GatsbyImage}
  sx={/* my sx styles */}
/>
Run Code Online (Sandbox Code Playgroud)

这就是我想要的。然而,我注意到该sxprop 以某种方式传递给了img. 这最终会<img sx=[object Object]/>在我的 HTML 中得到 a 。

虽然这并不会真正影响我的应用程序,但我想知道是否有更好的方法来实现这一目标?

Nea*_*arl 6

您可以使用该styled函数将sxprop 添加到自定义组件,如下所示:

import { styled } from "@mui/material/styles";

const ComponentWithSx = styled(YourCustomComponent)();
Run Code Online (Sandbox Code Playgroud)
<ComponentWithSx
  sx={{
    width: 30,
    height: 30,
    backgroundColor: "primary.dark"
  }}
/>
Run Code Online (Sandbox Code Playgroud)

当你将 传递GatsbyImage给 的componentprop 时BoxGatsbyImage被用作 内部的根组件Box,并且该sx对象被传递给 DOM 元素:

function Box(props) {
  const { component, ...other /* other includes sx prop */ } = props;
  return <component {...other} />;
});
Run Code Online (Sandbox Code Playgroud)

如果你想使用Box你需要创建一个包装组件来过滤sx道具:

function MyGatsbyImage({ sx, ...props }) {
  return <GatsbyImage {...props} />;
}
Run Code Online (Sandbox Code Playgroud)

Codesandbox 演示