【问题标题】:Module not found: Can't resolve 'material-ui/styles/colors'未找到模块:无法解析“material-ui/styles/colors”
【发布时间】:2018-09-19 22:19:44
【问题描述】:

我有以下未编译的代码:

import React from 'react';
import { AppBar, Toolbar } from 'material-ui';
import { Typography } from 'material-ui';
import { MuiThemeProvider, createMuiTheme } from 'material-ui/styles';
import {cyan, red} from 'material-ui/colors';
import { red400 } from 'material-ui/styles/colors';


const theme = createMuiTheme({
  palette: {
    primary: red400,
    secondary: cyan, 
  },
});

const View = (props) => (
  <MuiThemeProvider theme={theme}>
    <AppBar position="static">
      <Toolbar>
      <Typography variant="title">
        {props.title}
      </Typography>          
      </Toolbar>
    </AppBar>
  </MuiThemeProvider>
);
export default View;

上面写着:

Failed to compile
./src/Dashboard/AppBar/Views/View.js
Module not found: Can't resolve 'material-ui/styles/colors' in '/home/developer/Desktop/react-reason/example/src/Dashboard/AppBar/Views'  

我做错了什么?

【问题讨论】:

  • 你运行npm install material-ui@next 了吗?我遇到了类似的问题,因为我运行了npm install material-ui,它安装了旧版本
  • 我也认为使用red400 是不正确的。也许尝试primary: red[400] 并删除额外的import { red400 } from 'material-ui/styles/colors'
  • 我只安装了npm install material-ui@next。还不够吗?
  • 是的,只使用npm install material-ui@next 就足够了。我最好的猜测是问题出在导入语句import { red400 } from 'material-ui/styles/colors' 中。我建议删除它并仅使用import {cyan, red} from 'material-ui/colors'; 在我的项目中我这样使用它:import green from 'material-ui/colors/green'; 然后primary: green
  • primary:{main:red['A400']}

标签: javascript reactjs material-ui


【解决方案1】:

将 cmets 中的讨论移到此处:

确保您安装了next 版本的material-ui:

npm install material-ui@next

此导入语句不正确:

import { red400 } from 'material-ui/styles/colors'

应该是这样的:

import red from 'material-ui/colors/red';

这里,red 是文档中所说的“颜色对象”。 然后您可以使用它来创建您的主题对象,如下所示:

const theme = createMuiTheme({
  palette: {
    primary: {
      main: red[500], //OR red['A400'] for the accent range
      contrastText: '#fff', // The text color to use
      // You can also specify light, dark variants to use (it's autocomputed otherwise)
    }
    //You can also just assign the color object if the defaults work for you
    secondary: red,
    error: red
    //tonalOffset
    //contrastThreshold

  },
});

在上面的代码中,键 primary secondaryerror 接受颜色对象或“调色板意图”,这是一个看起来像这样的对象:

interface PaletteIntention {
  light?: string;
  main: string;
  dark?: string;
  contrastText?: string;
};

唯一需要的密钥是main。如果未提供,其余部分将根据 main 的值自动计算。

参考:

The docs have a detail section on themes which explains all of this in detail.

【讨论】:

  • 我提名你重写他们的官方文档。
  • 包 material-ui@next 已被弃用为 @material-ui/core
【解决方案2】:

试试这个

import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles';

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-20
    • 2018-02-16
    • 2018-03-30
    • 2021-10-24
    • 2019-02-02
    • 2020-03-18
    • 2021-10-12
    • 2020-09-09
    相关资源
    最近更新 更多