我是新來的React,我想添加一個簡單的「顯示更多」按鈕到我的應用程序。我有一個數據數組,我想在其中顯示3個條目作爲默認值。當用戶點擊show more
時,應該呈現其餘數據,並且按鈕應將文本更改爲show less
。我不確定如何去做。ReactJS如何添加顯示更多/顯示更少按鈕
這是我走到這一步:
class Application extends React.Component {
constructor() {
super()
this.cars = [
{ "name" : "Audi", "country" : "Germany"},
{ "name" : "BMW", "country" : "Germany" },
{ "name" : "Chevrolet", "country" : "USA" },
{ "name" : "Citroen", "country" : "France" },
{ "name" : "Hyundai", "country" : "South Korea" },
{ "name" : "Mercedes-Benz", "country" : "Germany" },
{ "name" : "Renault", "country" : "France" },
{ "name" : "Seat", "country" : "Spain" },
]
this.isLoaded = false
}
showMore() {
// show more entries
// switch to "show less"
}
render() {
return <div className="container">
<h3>Click show more to see more data</h3>
<div className="row">
<h3>List of Cars</h3>
<ul>
{this.cars.slice(0,3).map((car, i) => <li key={i}>{car.name} - {car.country}</li>)}
</ul>
</div>
<p>
<a className="btn btn-primary" onClick={this.showMore()}>Show more</a>.
</p>
</div>;
}
}
React.render(<Application />, document.getElementById('app'));
這裏是一個JSBin在行動代碼
有人能幫助我嗎?
isLoaded應該在你的狀態。要更新您的渲染,請調用setState。你可以有一個「state.itemNumber」,當你打電話給showMore時,你更新它的長度。在你的JSX中,slice(0,state.itemNumber)和你很好 – Nevosis