Next.js - 使用 CSS 模块时无法应用动态类名称

csj*_*es1 5 javascript css reactjs css-modules next.js

希望这里有人能帮我解决这个问题。

我正在尝试通过 NextJs 建立一个网站。我的其中一个页面有一些段落和按钮,它们的样式根据状态和事件而有所不同。在使用纯 React 时以及在 NextJs 中使用全局样式表时,我都可以使样式按预期工作;但是当我使用 CSS 模块时,我无法让它按预期运行。

(注意:我还可以通过使用简单的三元来使其工作,例如 <h1 className={submitted ? styles.showresult : styles.hideresult}>Correct? {correct}</h1>;但我还有一些其他场景,我需要依赖多个 if 并创建多个类,每个类都有自己的样式,所以我无法制作一个简单的三元我的最终解决方案。

例如,这是文件 pagex.js

import React from 'react';
import ReactDOM from 'react-dom';

const Pagex = () => {

const [submitted, setSubmitted] = React.useState(false); // whether the submit button was pressed

function calculateScore() {
  let correct = 0
  let incorrect = 0
    //......some scoring logic.....    
  setSubmitted(true)
  }

  // function to create a display class based on whether the submit button has been pressed
 function displayResult(){
   if (submitted === true) {
      return "showtheresult"
    } else {
         return "hidetheresult"
    }
  }

return (
  <section className="results">
      <h1 className={displayResult()}>Correct? {correct}</h1>
      <h1 className={displayResult()}>Incorrect? {incorrect}</h1>
  <button className={displayResult()} onClick={handleMovClick}>An instruction</button>
    </section>
    </div>
  );
};
export default Pagex;
Run Code Online (Sandbox Code Playgroud)

globals.css 文件包含

h1.hidetheresult, h3.hidetheresult {
  visibility: hidden;
}

h1.showtheresult, h3.showtheresult {
  visibility: visible;
}

button.hidetheresult {
    border-color: pink;
  }

button.showtheresult {
    border-color: aqua;
  }
Run Code Online (Sandbox Code Playgroud)

使用CSS模块时的变化

  1. 在正确的文件夹中添加具有正确名称 (../styles/Pagex.module.css) 的 CSS 文件,其中包含与上面所示相同的样式
  2. pagex.js 中的额外导入import styles from '../styles/Pagex.module.css'
  3. 更改 pagex.js 中函数的引用
    function displayResult(){
       if (submitted === true) {
          return {styles.showtheresult}
        } else {
             return {styles.hidetheresult}
        }
      }
Run Code Online (Sandbox Code Playgroud)

当我这样做时,'.' 并被vscode 突出显示为错误,并包含此详细信息:{styles.showtheresult},”预期。TS(1005)。 在尝试编译后,在运行开发服务器的情况下保存 js 会显示类似的消息:语法错误:意外的标记,预期为“,”,并且浏览器显示相同的消息以及{styles.hidetheresult}“编译失败”

也尝试过只是通过styles.showtheresult/styles.hidetheresult通过从 displayResult() 函数中删除大括号来可以编译,但编译后的网页上没有任何反应,即按下按钮时类不会更新,因此无法应用样式。

还尝试在 return 语句中传递 ${styles.showresult} 和 ${styles.hideresult} (带有 `)。这也可以编译,但页面本身给了我一个“未处理的运行时错误ReferenceError:样式未定义”消息,并且我无法加载页面。

如果有人可以帮助纠正我在函数本身或代码中其他地方的语法,我将不胜感激。

Psy*_*Gik 12

因为你问得好;)(开玩笑)

因此 Next.js 是一个固执己见的框架,并使用 CSS 模块来强制组件范围内的样式。

基本上,您可以使用name.module.css文件名定义样式表并在其中添加常规 CSS。

.hidetheresult {
    visibility: hidden;
}

.showtheresult{
    visibility: visible;
}
  
.btn-hidetheresult {
    border-color: pink;
}

.btn-showtheresult {
    border-color: aqua;
}
Run Code Online (Sandbox Code Playgroud)

现在要使用它,像任何 JS 模块一样导入它,

import styles from './styles.module.css'
console.log(styles);
// styles => {
//  hidetheresult: 'contact_hidetheresult__3LvIF',
//  showtheresult: 'contact_showtheresult__N5XLE',
//  'btn-hidetheresult': 'contact_btn-hidetheresult__3CQHv',
//  'btn-showtheresult': 'contact_btn-showtheresult__1rM1E'
//  }
Run Code Online (Sandbox Code Playgroud)

如您所见,样式已转换为对象,现在您可以像styles.hidetheresult或 一样使用它们styles['btn-hidetheresult']

请注意样式表中缺少元素选择器。这是因为 CSS 模块重写了类名称,但它们不触及标签名称。在 Next.js 中,这是默认行为。即它不允许元素标签选择器。

文件扩展名*.module.(css | scss | sass)是 css 模块,它们只能使用类名或 id 定位元素,而不能使用标签名称。虽然这在 create-react-app 等其他框架中是可能的,但在 next-js 中是不可能的。

但您可以在文件中覆盖它next.config.js。(超出本回答范围)

有一篇文章解释了如何覆盖它。- 免责声明:我是作者


现在来到您的用例,您可以像这样进行条件样式设置:(假设样式符合答案中给出的示例)

import React from "react";
import styles from "./styles.module.css";

const PageX = () => {
  const [submitted, setSubmitted] = React.useState(false);

  const getStyle = () => {
    if (submitted) return styles.showtheresult;
    else return styles.hidetheresult;
  };

  const getButtonStyle = () => {
    if (submitted) return styles["btn-showtheresult"];
    else return styles["btn-hidetheresult"];
  };

  return (
    <div>
      <section className="results">
        <h1 className={getStyle()}>Correct?</h1>
        <h1 className={getStyle()}>Incorrect?</h1>
        <button className={getButtonStyle()} onClick={handleMovClick}>
          An instruction
        </button>
      </section>
    </div>
  );
};

Run Code Online (Sandbox Code Playgroud)

当添加更多条件时,方法往往会变得更加复杂。这就是类名 模块派上用场的地方。

import styles from "./styles.module.css";
import clsx from "classnames";

const PageX = () => {
  const [submitted, setSubmitted] = React.useState(false);

  const headerStyle = clsx({
    [styles.showtheresult]: submitted,
    [styles.hidetheresult]: !submitted,
  });
  const btnStyle = clsx({
    [styles["btn-showtheresult"]]: submitted,
    [styles["btn-hidetheresult"]]: !submitted,
  });
  return (
    <div>
      <section className="results">
        <h1 className={headerStyle}>Correct?</h1>
        <h1 className={headerStyle}>Incorrect?</h1>
        <button className={btnStyle} onClick={handleMovClick}>
          An instruction
        </button>
      </section>
    </div>
  );
};
Run Code Online (Sandbox Code Playgroud)

这是一个 CodeSandbox 供您使用: 编辑 68554803-next-js-cant-apply-dynamic-class-names