【发布时间】:2019-09-27 15:23:15
【问题描述】:
我正在使用 React 开发一个个人投资组合,它从 json 获取数据并呈现它。项目组成部分是我遇到一些困难的地方。我在类别下渲染项目,但我的问题是我创建了一个切换滑块选择器,我可以在其中选择一个类别,但我不知道如何根据当前状态更改滑块选项的类名。
代码如下:
import React, { Component } from 'react';
import SectionWrap from './sectionWrap';
class Projects extends Component {
state = {
switchState: "All"
}
// renderProjects function is just rendering jsx based on imported json file (nothing important)
switchCurrentState = (e) => {
e.preventDefault();
this.setState({
switchState: e.target.innerHTML
})
}
render() {
return (
<SectionWrap id="projects" name="Projects">
<div className="switchWrap">
<a className="switch" href="#" onClick={this.switchCurrentState}>All</a>
<a className="switch" href="#" onClick={this.switchCurrentState}>Graphic</a>
<a className="switch" href="#" onClick={this.switchCurrentState}>Web</a>
<a className="switch" href="#" onClick={this.switchCurrentState}>Photography</a>
<a className="switch switchOn" href="#" onClick={this.switchCurrentState}>Video</a>
</div>
<div className="projectsWrap">
{this.state.switchState == "All" ? this.renderProjects("All") : this.renderProjects(this.state.switchState)}
</div>
</SectionWrap>
);
}
}
export default Projects;
我想要做的是在开关处于活动状态时添加一个类名“switchOn”,例如:
className={`switch ${this.state.switchState === this.value ? 'switchOn' : ''}`
this.value 是 div 的值/文本。
【问题讨论】:
-
首先在您的 onClick 处理程序上,您需要将它们顶部绑定 {this.switchCurrentCase.bind(this)} 要根据状态设置一个类,您几乎拥有它.. className={this.state. switchState ===“全部”? "switchOn" : ""} 您必须专门检查每个链接上的每个类别。此外,您应该使用按钮而不是锚标签。 .
标签: javascript reactjs