这是使用新的钩子语法执行此操作的示例:
index.js
import React from "react";import ReactDOM from "react-dom";import StyledComponent from "./StyledComponent";const CustomComponent = ({ children, className }) => { return ( <p className={className}> Just showing passing in the component to use rather than automatically using a div. <br /> {children} </p> );};function App() { return ( <div className="App"> <StyledComponent color="green"> Here's my content with green underline </StyledComponent> <StyledComponent component={CustomComponent} color="blue" hoverColor="orange" > Here's my content with blue underline that changes to orange on hover. </StyledComponent> </div> );}const rootElement = document.getElementById("root");ReactDOM.render(<App />, rootElement);StyledComponent.js
import React from "react";import { makeStyles } from "@material-ui/styles";const useStyles = makeStyles({ root: { borderBottom: ({ color }) => `2px solid ${color}`, "&:hover": { borderBottom: ({ color, hoverColor }) => { const borderColor = hoverColor ? hoverColor : color; return `2px solid ${borderColor}`; } } }});const StyledComponent = ({ component: ComponentProp = "div", children, color, hoverColor}) => { const classes = useStyles({ color, hoverColor }); return <ComponentProp className={classes.root}>{children}</ComponentProp>;};export default StyledComponent;如果您愿意,可以将此
useStyles方法放在自己的文件中,然后将其用作自定义钩子,以使它生成的类(仍然具有变量支持)可用于多个组件(而不仅仅是
StyledComponent)。



