我的应用程序中有页码。现在,当我单击页码时,单击或当前页码不会突出显示或以其他颜色显示。我有一个className =“ text-success”,如果添加,它将使文本变为绿色。我想将其动态添加到单击的数字。我应该怎么做
这是分页div(第nunbers页)
<div className="pagination-media">
<a href="#" onClick={this.getPreviousPage} className="text-success">
<span className="fa fa-chevron-left"></span>
PREV
</a>
{page_number_array.map((item, i) => (
<a href="#" id={`page-${item}`} className="page-no-m"
onClick={() => this.pageNumberClicked(item)}>{`${item} `}</a>
)
)}
<a href="#" onClick={this.getNextPage}
className="text-success"><b>NEXT</b>
<span className="fa fa-chevron-right"></span></a>
</div>
最佳答案
您需要保存currentPage
状态以了解当前活动页面是什么。然后,您可以有条件地将text-success
类添加到每个链接:
let page_number_array = [1,2,3,4,5];
class App extends React.Component {
constructor() {
super();
this.state = {
currentPage: 1
}
}
pageNumberClicked = num => {
this.setState({
currentPage: num
});
}
getPreviousPage = () => {
this.setState({
currentPage: this.state.currentPage - 1 > 0 ? this.state.currentPage - 1 : 1
});
}
getNextPage = () => {
this.setState({
currentPage: this.state.currentPage + 1 <= page_number_array.length ? this.state.currentPage + 1 : 1
});
}
render() {
return (
<div className="pagination-media">
<a href="#" onClick={this.getPreviousPage} className="text-success">
<span className="fa fa-chevron-left"></span>
PREV
</a>
{page_number_array.map((item, i) => (
<a
href="#"
id={`page-${item}`}
className={`${this.state.currentPage === item ? 'text-success' : ''} page-no-m`}
onClick={() => this.pageNumberClicked(item)}
>
{`${item} `}
</a>
))}
<a href="#" onClick={this.getNextPage}
className="text-success">
<b>NEXT</b>
<span className="fa fa-chevron-right"></span>
</a>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('root'));
.text-success {
color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
关于javascript - 突出显示单击的页码,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47080234/