gpt4 book ai didi

reactjs - 如何组合来自父组件和子组件的 makeStyle 类?

转载 作者:行者123 更新时间:2023-12-04 01:21:38 26 4
gpt4 key购买 nike

如何将 makeStyle 类从父组件传递到子组件并将它们与子组件中的 makeStyle 类组合?例如。如下添加断点隐藏到子组件样式。
示例子组件:

import React from "react"
import { Button } from "@material-ui/core"
import { makeStyles } from "@material-ui/core/styles"

const useStyles = makeStyles(theme => ({
button: {
background: "#000",
color: "white",
//lots of other css here so we dont want to repeat it in the parent component

},
}))

export default function PrimaryButton(props) {
const classes = useStyles()
const { children, fullWidth = false } = props

return (
<Button
fullWidth={fullWidth}
className={classes.button}
variant="contained"
>
{children}
</Button>
)
}

示例父组件:

import React from "react"
import { PrimaryButton } from "components/PrimaryButton"
import { makeStyles } from "@material-ui/core/styles"

const useStyles = makeStyles(theme => ({
primaryButton: {
display: "inline-block",
[theme.breakpoints.down("sm")]: {
display: "none",
},
},
}))

export default function PrimaryButton(props) {
const classes = useStyles()

return (
<PrimaryButton
className={classes.primaryButton}
>
Button text
</PrimaryButton>
)
}

最佳答案

clsx在 Material-UI 内部使用,是组合多个类名的方便实用程序。在您的子组件中,您可以抓取 className从 Prop 然后使用className={clsx(className, classes.button)}Button它呈现:

import React from "react";
import { Button } from "@material-ui/core";
import { makeStyles } from "@material-ui/core/styles";
import clsx from "clsx";

const useStyles = makeStyles(theme => ({
button: {
background: "#000",
color: "white"
}
}));

export default function PrimaryButton(props) {
const classes = useStyles();
const { children, className, fullWidth = false } = props;

return (
<Button
fullWidth={fullWidth}
className={clsx(className, classes.button)}
variant="contained"
>
{children}
</Button>
);
}
Edit combine class names

关于reactjs - 如何组合来自父组件和子组件的 makeStyle 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62561123/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com