In the 官方迁移指南 https://next.material-ui.com/guides/migration-v4/#main-content,他们给出了以下从 JSS 更改代码的示例(makeStyles
)到新的styled
mode.
Before:
const useStyles = makeStyles((theme) => ({
background: theme.palette.primary.main,
}));
function Component() {
const classes = useStyles();
return <div className={classes.root} />
}
After:
const MyComponent = styled('div')(({ theme }) =>
({ background: theme.palette.primary.main }));
function App(props) {
return (
<ThemeProvider theme={theme}>
<MyComponent {...props} />
</ThemeProvider>
);
}
对于单个类来说这很好,但是当代码中有条件类时该怎么办?
e.g.
<main className={classnames(content, open ? contentOpen : contentClosed)}>
{/* content goes here */}
</main>
Here, content
, contentOpen
, and contentClosed
类是从返回的useStyles
, but contentOpen
and contentClosed
根据以下值有条件地呈现open
.
随着新styled
方法,我们不是生成类名,而是生成组件。有没有一种方法可以优雅地复制渲染,而无需在三元表达式中进行内容重复?
e.g. we don't想做类似的事情:
function App(props) {
return (
<ThemeProvider theme={theme}>
{open
? <MyOpenComponent {...props}>{/* content */}</MyOpenComponent>
: <MyClosedComponent {...props}>{/* content */}</MyClosedComponent>
</ThemeProvider>
);
}