javascript - 将 Typescript 与样式化组件和 Material UI 结合使用

标签 javascript reactjs typescript material-ui styled-components

将 Typescript 与 MUI+Styled-Components 结合使用,由于类型错误,您必须直接将 props 传递给 MUI 元素......

const Index = () => {
  return (
      <StyledButton
        variant="contained"
      >
        Hello World
      </StyledButton>
   )}


const StyledButton = styled(Button)`
  background: red;
  color: white;
`;

但是,这会出现以下错误:

键入'{ children: string;变体:“包含”; }' 不可分配给类型 '(IntrinsicAttributes & Pick>) | PropsWithChildren,“形式” | “风格” | “标题” | ... 284 更多 ... | “变体”>&部分<...>,“形式” | ... 286 更多... | “变体”> & { ...; } & { ...; }) | (IntrinsicAttributes & ... 3 more ... & { ...; })’

当你像下面这样直接传入 props 时,这个错误就会消失。即使在 Styled MUI 元素上使用 0 个 Prop 和 0 个子元素,它也会出现错误。

const StyledButton = styled(props => <Button {...props} />)`
  background: red;
  color: white;
`;

最佳答案

这应该适用于 MUI >= 4.*

对于早期版本,来自 this tutorial ,尝试强制执行 StyledButton 的类型:

const StyledButton = styled(Button)`
  background: red;
  color: white;
` as typeof(Button);

关于javascript - 将 Typescript 与样式化组件和 Material UI 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55619423/

相关文章:

javascript - typescript 错误 'argument of type is not assignable to parameter of type'

typescript ,对象的类型为 'unknown'

reactjs - iframe 的 useRef 使用什么类型

javascript - 为什么对我的指令使用 ng-repeat 会对我的绑定(bind)产生影响?

javascript - res.render 中的 Express-Node JS Handlebars 模板 : How to iterate?

javascript - 消息的正则表达式

javascript - React-Redux 中的页面加载时未调度操作

javascript - Jquery 下拉菜单,如何在我的容器 div 中定位

css - 情感 css 样式使用与示例相同的代码给我错误

reactjs - 为什么我的 react 路由器调用 api 两次?