【发布时间】:2021-07-29 02:30:26
【问题描述】:
希望这里有人能帮我解决这个问题。
我正在尝试通过 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 模块时的变化
- 在正确的文件夹中添加一个名称正确的 CSS 文件 (../styles/Pagex.module.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}(带 `)。这也可以编译,但页面本身给了我一个 "Unhandled Runtime Error ReferenceError: styles is not defined" 消息,我无法加载页面。
如果有人可以帮助纠正我在函数本身或代码其他地方的语法,我们将不胜感激。
【问题讨论】:
-
您可以使用 classnames 模块,该模块是为有条件地添加多个类名的确切用例而编写的
-
嗨@PsyGik 感谢您的反馈和指导。我一定会看一下该模块,但您能否帮助纠正我在示例中的语法以使其在不需要依赖类名模块的情况下工作?或者您是否表明这是一个限制而不是语法错误,并且解决它的方法是包含 classnames 模块?
标签: javascript css reactjs next.js css-modules