gpt4 book ai didi

javascript - 突出显示单击的页码

转载 作者:行者123 更新时间:2023-12-03 03:08:04 24 4
gpt4 key购买 nike

我的 react 应用程序中有页码。现在,当我单击页码时,单击或当前页码不会突出显示或以不同的颜色显示。我有一个 className="text-success"如果添加它将使文本变为绿色。我想将其动态添加到单击的数字中。我该怎么做

这是分页div(页码)

<div className="pagination-media">
<a href="#" onClick={this.getPreviousPage} className="text-success">
<span className="fa fa-chevron-left"></span> &nbsp;
PREV
</a> &nbsp;
{page_number_array.map((item, i) => (
<a href="#" id={`page-${item}`} className="page-no-m"
onClick={() => this.pageNumberClicked(item)}>{`${item} `}</a>
)
)}
&nbsp;

<a href="#" onClick={this.getNextPage}
className="text-success"><b>NEXT</b> &nbsp;
<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>
&nbsp;PREV
</a> &nbsp;
{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>
))}
&nbsp;
<a href="#" onClick={this.getNextPage}
className="text-success">
<b>NEXT</b> &nbsp;
<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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com