@material-ui/styles
支持下一种重新定义默认样式的方法:
import React from 'react';
import Box from '@material-ui/core/Box';
import { styled } from '@material-ui/core/styles';
const StyledBox = styled(Box)({
color: 'red'
});
默认情况下,Box
就像<div />
,我可以通过传递component
道具来更改它:
// somewhere in code
<StyledBox
component="span"
>
Some text
</StyledBox>
这个例子不起作用:
import React from 'react';
import Box from '@material-ui/core/Box';
import { styled } from '@material-ui/core/styles';
const StyledBox = styled(<Box component="span" />)({
color: 'red'
});
在设计阶段是否可以使用styled
为Box定义组件?
答案 0 :(得分:1)
下面是显示如何执行此操作的示例。您无法将<Box component="span" />
(元素)传递给styled
,因为它期望组件类型不是元素(即组件的实例)。相反,您需要创建一个新的组件类型(在下面的示例中为SpanBox
),该组件类型包装Box
并通过任何props或ref传递,同时指定要控制的props(例如component="span"
)
import React from "react";
import Box from "@material-ui/core/Box";
import { styled } from "@material-ui/core/styles";
const StyledBox = styled(Box)({
color: "red"
});
const SpanBox = React.forwardRef(function SpanBox(props, ref) {
return <Box ref={ref} component="span" {...props} />;
});
const StyledSpanBox = styled(SpanBox)({
color: "purple"
});
export default function App() {
return (
<div className="App">
<StyledBox>red div 1</StyledBox>
<StyledBox>red div 2</StyledBox>
<StyledSpanBox>purple span 1</StyledSpanBox>
<StyledSpanBox pl={3} border={1}>
purple span 2
</StyledSpanBox>
</div>
);
}