javascript - Next.js - 使用 CSS 模块时无法应用动态类名
问题描述
希望这里有人可以帮我解决这个问题。
我正在尝试通过 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;
globals.css 文件包含
h1.hidetheresult, h3.hidetheresult {
visibility: hidden;
}
h1.showtheresult, h3.showtheresult {
visibility: visible;
}
button.hidetheresult {
border-color: pink;
}
button.showtheresult {
border-color: aqua;
}
使用 CSS 模块时的更改
- 在正确的文件夹中添加一个具有正确名称 (../styles/Pagex.module.css) 的 CSS 文件,其中包含与上面显示的相同样式
- pagex.js 中的附加导入
import styles from '../styles/Pagex.module.css'
- 更改 pagex.js 中函数的引用
function displayResult(){
if (submitted === true) {
return {styles.showtheresult}
} else {
return {styles.hidetheresult}
}
}
当我这样做时'。在{styles.showtheresult}
并被{styles.hidetheresult}
vscode 突出显示为错误,并带有以下详细信息:“,”预期。ts(1005)。
在尝试编译后,在运行开发服务器的情况下保存 js 会显示类似的消息:语法错误:意外的令牌,预期的“”,并且浏览器显示相同的消息以及“编译失败”
还尝试通过从 displayResult() 函数中删除花括号来传递styles.showtheresult
/ 。styles.hidetheresult
编译但在编译的网页上没有任何反应,即按下按钮时类不会更新,因此无法应用样式。
还尝试在 return 语句中传递为 ${styles.showresult} 和 ${styles.hideresult} (带 `)。这也可以编译,但页面本身给了我“未处理的运行时错误 ReferenceError:未定义样式”消息,我无法加载页面。
如果有人可以帮助纠正我在函数本身或代码其他地方的语法,将不胜感激。
解决方案
因为你问得很好;)(开个玩笑)
所以 Next.js 是一个自以为是的框架,它使用 CSS 模块来强制组件范围样式。
基本上,您使用name.module.css
文件名定义样式表并在其中添加常规 CSS。
.hidetheresult {
visibility: hidden;
}
.showtheresult{
visibility: visible;
}
.btn-hidetheresult {
border-color: pink;
}
.btn-showtheresult {
border-color: aqua;
}
现在要使用它,像任何 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'
// }
如您所见,样式已转换为对象,现在您可以像styles.hidetheresult
或一样使用它们styles['btn-hidetheresult']
。
注意样式表中没有元素选择器。那是因为 CSS 模块重写了类名,但它们不涉及标签名。在 Next.js 中,这是默认行为。即它不允许元素标签选择器。
文件扩展名
*.module.(css | scss | sass)
是 css 模块,它们只能使用类名或 id 来定位元素,而不能使用标签名。虽然这在 create-react-app 等其他框架中是可能的,但在 next-js 中是不可能的。
但是您可以在next.config.js
文件中覆盖它。(超出此答案的范围)
有一篇文章解释了如何覆盖它。- 免责声明:我是作者
现在来到您的用例,您可以像这样进行 contitional 样式:(假设样式与答案中给出的示例一致)
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>
);
};
随着您添加更多条件,这些方法确实会变得更加复杂。这就是类名 模块派上用场的地方。
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>
);
};
推荐阅读
- angular - 将数据从角度应用程序传递到角度库
- javascript - 在 Highcharts 中指定区域中的模式时如何使用默认颜色
- c# - dotnet cli how to create project using previous sdk/framework?
- github - 尽管成功创建了部署密钥,Github 仍然要求提供凭据?
- python - Creating a pandas Series with numpy
- angular - Angular - 向后和向前迭代数组未定义
- flutter - Flutter swiper disable swipe when last index
- javascript - 更新查询参数 Node.js
- c# - ASP.NET Core 2.2 Upgrade - IIS: limit request content length
- python - Convert to NaN if cell is in the top or bottom x%