如何在styled-components中覆盖material-ui的嵌套类?

3
Method 1:
const StyledTextField = styled(({ ...rest }) => (
  <OutlinedInput {...rest} classes={{ root: 'outlinedRoot' }} />
))`
  .outlinedRoot {
    .$notchedOutline {
      border-color: red;
    }
  }
  background: #fff;
  border-radius: 4px;
  color: #808080;
  height: 53px;
`;

Method 2:
const StyledTextField = styled(OutlinedInput).attrs({
  classes: { root: 'outlinedRoot', notchedOutline: 'notchedOutline' }
})`
  .outlinedRoot {
    .notchedOutline {
      border-color: red;
    }
  }
  background: #fff;
  border-radius: 4px;
  color: #808080;
  height: 53px;
`;

我也看到了需要添加的类别并阅读了相关文章,但我无法覆盖它们。

我尝试了上述两种方法来更改轮廓线颜色,但我无法做到这一点。

1个回答

3
以下是一个实现的示例。如果要使用 TextField 而不是 OutlinedInput,只需在 .MuiOutlinedInput-root 之前添加一个空格,以便将其匹配为 TextField 的后代,而不是将其作为根元素上的其他类之一进行匹配。实际上,.MuiOutlinedInput-root 对于样式来说是不必要的,除了有助于 CSS 特异性。
import React from "react";
import ReactDOM from "react-dom";

import OutlinedInput from "@material-ui/core/OutlinedInput";
import styled from "styled-components";

const StyledOutlinedInput = styled(OutlinedInput)`
  &.MuiOutlinedInput-root .MuiOutlinedInput-notchedOutline {
    border-color: green;
  }
  &:hover.MuiOutlinedInput-root .MuiOutlinedInput-notchedOutline {
    border-color: red;
  }
  &.MuiOutlinedInput-root.Mui-focused .MuiOutlinedInput-notchedOutline {
    border-color: purple;
  }
`;

function App() {
  return (
    <div className="App">
      <StyledOutlinedInput defaultValue="My Default Value" />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

自定义轮廓 styled-components

相关答案:


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接