【发布时间】:2018-01-29 16:52:07
【问题描述】:
我制作了 2 个组件: 1) 内容(使用 fetch() 显示数据) 2)分页(共5页,每页16个对象)
我创建了两个状态变量,分别称为 start:0 和 end:16。现在,每当用户单击页码时,我都想将开始和结束状态变量从分页组件注入到内容组件。
将开始和结束变量传递给内容的逻辑如下: 最初 end=16*1 (因为第 1 页而乘以 1)和 start= end-16 即 start=0
end = 16*2(因为第 2 页而乘以 2)和 start=end-16 即 start=16
这些开始和结束变量在内容组件的.slice() 中传递,以便onClick:
第 1 页应该显示文章 0 到 16
第 2 页应该显示第 16 到 32 条,依此类推,直到第 5 页
下面是分页和内容组件的代码:
content.js:
class Content extends Component {
constructor(props){
super(props);
this.state = {
matches:[],
loading:true,
callmatchinfo: false,
matchid:''
};
}
componentDidMount(){
fetch('api/matches')
.then(res => res.json())
.then(res => {
console.log(res)
this.setState({
matches:res.slice(this.props.start,this.props.end), <---add new start and end everytime we click on new page number
loading:false
});
})
}
viewstats(matchid){
this.setState({
callmatchinfo: true,
matchid: matchid
});
}
rendermatchinfo(){
return <Matchinfo matchid={this.state.matchid} />
}
renderMatches() {
return this.state.matches.map(match => {
return (
<div className="col-lg-3">
<div id="content">
<p className="match">MATCH {match.id}</p>
<h4>{match.team1}</h4>
<p>VS</p>
<h4>{match.team2}</h4>
<div className="winner">
<h3>WINNER</h3>
<h4>{match.winner}</h4>
</div>
<div className="stats">
<button type="button" onClick= {()=>{this.viewstats(match.id)}} className="btn btn-success">View Stats</button>
</div>
</div>
</div>
);
})
}
render() {
if (this.state.loading) {
return <img src="https://upload.wikimedia.org/wikipedia/commons/b/b1/Loading_icon.gif" />
}
else if(this.state.callmatchinfo){
return <Matchinfo match_id={this.state.matchid} />
}
return (
<div>
<div className="row">
{this.renderMatches()}
</div>
<div className="row">
{this.state.callmatchinfo ? this.rendermatchinfo() : ''}
</div>
</div>
);
}
}
export default Content;
分页.js:
class Pagination extends Component {
constructor(props){
super(props)
this.state = {
start:0,
end:16
};
}
handleClick(){
this.setState{
end:getpagenumber()*16,
start:end-16
}
}
getpagenumber(val){
return val;
}
render() {
let{start,end} = this.state;
return (
<div>
<Content/>
<div className="container">
<ul className="pagination">
<li {this.getpagenumber(1)} onClick={this.handleClick}><a href="#">1</a></li>
<li {this.getpagenumber(2)} onClick={this.handleClick}><a href="#">2</a></li>
<li {this.getpagenumber(3)} onClick={this.handleClick}><a href="#">3</a></li>
<li{this.getpagenumber(4)} onClick={this.handleClick}><a href="#">4</a></li>
<li{this.getpagenumber(5)} onClick={this.handleClick}><a href="#">5</a></li>
</ul>
</div>
</div>
);
}
}
export default Pagination;
【问题讨论】:
标签: reactjs