css - 将 onHover 样式应用于 MuiButton 中的元素

标签 css reactjs typescript material-ui styled-components

我正在使用样式化组件和 Material UI,但我不知道如何添加 MuiButton 子项的悬停样式。我在网上搜索并遵循了一些文档,但我似乎无法接受它。我的 jsx 设置如下:

<StyledMuiButton onClick={() => ()}>
  <Svg />
  <MuiTypography color={Color.gray} variant="caption">
    Text
   </MuiTypography>
</StyledMuiButton>

样式组件设置如下:

const StyledMuiButton = styled(MuiButton)`
  && {
    & .MuiButton-label {
      flex-direction: column;
    }

    &:hover ${MuiTypography} {
      color: ${Color.primary};
    }
  }
`;

谁能给我指出正确的方向

最佳答案

下面的示例展示了在按钮内定位元素的几种方法:

import React from "react";
import Button from "@material-ui/core/Button";
import Typography from "@material-ui/core/Typography";
import DoneIcon from "@material-ui/icons/Done";
import styled from "styled-components";

const StyledButton = styled(Button)`
  & .MuiButton-label {
    display: flex;
    flex-direction: column;
  }
  &:hover {
    color: red;
    .MuiSvgIcon-root {
      background-color: blue;
    }
    .MuiTypography-root {
      color: green;
      &:nth-of-type(2) {
        color: purple;
      }
    }
  }
`;

export default function App() {
  return (
    <div className="App">
      <Button>Default Button</Button>
      <StyledButton>Styled Button</StyledButton>
      <StyledButton>
        <DoneIcon />
        <span>Styled Button</span>
        <Typography>Typography 1</Typography>
        <Typography>Typography 2</Typography>
      </StyledButton>
    </div>
  );
}

Edit styled-components hover button

这利用了应用于元素的全局类名,这些元素记录在每个组件的 API 页面的 CSS 部分中(例如排版文档位于: https://material-ui.com/api/typography/#css )。作为一般规则,Material-UI 组件中最顶层的元素可以通过 MuiComponentName-root 定位(例如 MuiTypography-root for Typography )。

关于css - 将 onHover 样式应用于 MuiButton 中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60644085/

相关文章:

typescript - 为什么这段代码没有给我一个带有 --noImplicitAny 的错误?

javascript - IE8 - 按钮背景图像不显示?

html - 图标与文字对齐

javascript - JQuery:如何为动态添加的元素添加一个id?

reactjs - 在 React Native 中使用 moment

reactjs - 极慢的 React 列表渲染

Onsen UI 的 TypeScript 定义

html - 如何删除 SlickGrid 中的标题?

javascript - Antd 多重选择删除不再出现在选项列表中的值

reactjs - React - IntrinsicAttributes 类型上不存在属性