我对 sass 和 React 还很陌生。我在搜索时没有找到这个确切的问题。任何建议,将不胜感激。我使用 React、socket io、node 和 sass 编写了一个基本的实时应用程序。我试图记录哪些用户在线/离线。我想通过根据它们是否具有与空间的事件套接字连接来显示绿色或红色圆圈来做到这一点。为此,我使用了一个映射和一个三元运算符。这部分工作没有问题:
render() {
console.log(this.props);
const members = this.props.users.map((user, i) => {
console.log(user);
return <li key={i} className={"member-info " + (user.active ?
'online' : 'offline')}>
<h2>{user.username}<div className="circle"></div></h2>
<h4>Joined: {moment(user.joined).format("MMM Do YY")}</h4>
</li>
})
在线用户申请在线类(class),离线用户申请离线类(class)。我想使用这个值来确定下面列表中圆圈 (className = circle) 的填充。我已经尝试了几种变体,但还没有让它发挥作用。因此,如果用户在线,我希望圆圈的背景色为绿色,如果离线,则为红色。这是我这部分的 sass 代码。成员是 ul,成员信息是 li。任何关于如何完成上述颜色变化的建议将不胜感激:
.members{
border: 1px solid gray;
background-color: royalblue;
color: white;
max-height: 45%;
overflow-y: scroll;
.member-info{
border: 1px solid gray;
padding: 10px;
a{
text-decoration: none;
color: white;
a:visited { text-decoration: none; }
a:hover { text-decoration: underline; }
a:focus { text-decoration: none; }
a:hover, a:active { text-decoration: underline; }
}
}
}
预先感谢您提出任何建议。
最佳答案
试试这个:
render() {
return (
<ul>
{this.props.users.map((user, i) => {
return (
<li
key={i}
// You might not need className on the <li>
>
<h2>
{user.username}
<div
className={`circle ${
user.active ? "circle--online" : "circle--offline"
}`}
/>
</h2>
<h4>Joined: {moment(user.joined).format("MMM Do YY")}</h4>
</li>
);
})}
</ul>
);
}
然后是你的 SASS:
.circle {
&--online {
color: green;
}
&--offline {
color: red;
}
}
有几件事我推荐。
考虑为您的组件设置一个“默认”状态,然后有条件地应用修饰符。而不是...
"member-info " + (user.active ? "online" : "offline")
...尝试将“离线”视为您的默认状态,然后有条件地添加“在线”作为您唯一的修饰符。
有一个非常轻量级的包(零依赖)叫做 classnames .它允许您更轻松地构建条件类字符串:
import classNames from "classnames";
const classes = classNames("member-info", {
"member-info--online": true // <-- String: Boolean
}); // => "member-info member-info--online"
通过只有一个默认状态和一个修改后的状态,我可以删除上面一半的 SASS。假设“circle”本身表示离线,“circle--online”表示在线:
.circle {
color: red;
&--online {
color: green;
}
}
这个带有双破折号的命名约定称为 BEM ,它非常适合 SASS。
关于css - 使用三元运算符在 sass/React 中有条件地应用类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50499901/