【问题标题】:CSS Modules don't return classCSS 模块不返回类
【发布时间】:2018-09-16 00:37:45
【问题描述】:

我想将 css 模块安装到 create-react-app 中,我遇到了这个 https://github.com/kitze/custom-react-scripts

设置完成后,我在我的文件夹中创建了一个测试style.module.css 文件并使用import styles from './style.module.css'; 像这样导入它,

import React, { Component } from 'react';
import styles from './style.module.css';

console.log(styles); //returns '/static/media/style.module.b3708639.css'
console.log(styles.red); //returns 'undefined'

export default class Form extends Component {
    render = () => {
        return (
            <form onSubmit={this.handleSubmit}>
                <TextInput />
                <PasswordInput />
                <Submit />
                <p className={[styles.red, 'test'].join(' ')}>Test</p> //rendered <p class="test">Test</p>
            </form>
        );
    }

    handleSubmit = () => {
        console.log('submit!');
    } 
}

这是我的 style.module.css 内容

.facebook_button { margin-top:10px; }
.red { color:red; }

有什么建议吗?

【问题讨论】:

  • CSS 不能像这样使用 JS 打印出来。相反,创建一个类似的 html 元素:&lt;h1 class="red"&gt;This should be red&lt;/h1&gt;
  • 我正在使用来自 create-react-app 的 react 和 custom-react-scripts fork,试图将 CSS 模块与我的组件一起使用。您指的是传统的 css html 输入。也许我应该用代码更明确地编辑我的问题。
  • 问起来可能很简单,但你检查过你有REACT_APP_CSS_MODULES=true吗?
  • 是的,我有 REACT_APP_CSS_MODULES = true;REACT_APP_CSS_MODULE_CLASSNAME_TEMPLATE = 'module-[sha512:hash:base32]-[name]-[local]';
  • 嗯,这很完美,我现在正在尝试,我让它显示完美的红色测试文本。可能是您的 // 呈现的评论没有帮助吗?尝试用花括号包裹它?

标签: reactjs css-modules custom-react-scripts


【解决方案1】:

应该从一开始就将custom-react-scripts 安装为脚本版本。

像这样:

create-react-app my-app --scripts-version custom-react-scripts

否则,如果在同一应用上使用 CRA 本身后安装,它将为其提供指向静态文件的 /static/media/ 路由,这不会为您在导入它的文件中提供您期望的样式对象。

【讨论】:

    猜你喜欢
    • 2017-02-26
    • 1970-01-01
    • 2020-12-29
    • 1970-01-01
    • 2020-09-07
    • 1970-01-01
    • 1970-01-01
    • 2016-05-14
    • 2020-05-19
    相关资源
    最近更新 更多