首先,電影應該按評分遞增排序,我做到了,但是當你點擊日期(僅限日期)時,它應該按日期遞減排序。如何才能做到這一點?我的代碼中的第二個問題,遞減和遞增無限作業,但它們必須只作業一次( 1 或 -1 就是這樣)。
import React from "react";
class App extends React.Component {
constructor() {
super()
this.state = {
movies: [
{ id: 1, name: "Deadpool", date: 2016, time: 108, genre: 'action', rating: 5 },
{ id: 2, name: "The Avengers", date: 2012, time: 143, genre: 'action', rating: 4 },
{ id: 3, name: "Slayers", date: 2022, time: 88, genre: 'fantasy,comedy', rating: 3 },
]
}
this.state.movies.sort((a,b) => a.rating > b.rating ? 1 : -1);
}
star(i) {
let arr = new Array(i);
return arr.fill("*");
}
remove(index) {
this.state.movies.splice(index, 1);
this.setState({});
}
increment(plus) {
plus.rating = plus.rating 1;
this.setState({});
}
decrement(minus) {
minus.rating = minus.rating - 1;
this.setState({});
}
render() {
return <>
<h1>Cinemas</h1>
<table className="table table-dark table-striped">
<thead>
<tr>
{
Object.keys(this.state.movies[0]).map((elem, ind) => {
return <th key={ind}>{elem}</th>
})
}
<th>stars</th>
</tr>
</thead>
<tbody>
{
this.state.movies.map((elm,index) => {
return <tr>
<td>{elm.id}</td>
<td>
{elm.name}
<button className="btn btn-primary ms-4" onClick={this.remove.bind(this, index)}>del</button>
</td>
<td>{elm.date}</td>
<td>{elm.time}</td>
<td>{elm.genre}</td>
<td>{elm.rating}</td>
<td>
{this.star(elm.rating)}
<button className="btn btn-primary ms-4" onClick={this.increment.bind(this, elm)}>Increment</button>
<button className="btn btn-primary ms-4" onClick={this.decrement.bind(this, elm)}>Decrement</button>
</td>
</tr>
})
}
</tbody>
</table>
</>
}
}
export default App
謝謝你。
uj5u.com熱心網友回復:
為了能夠按日期排序,您可以使用如下所示的函式,并在單擊日期單元格時呼叫它,該單元格將轉換為按鈕:
sortByDecreasingDate() {
this.setState({
...this.state,
movies: this.state.movies.sort(
(a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()
)
});
}
<thead>
<tr>
{Object.keys(this.state.movies[0]).map((elem, ind) => {
if (elem === "date") {
return (
<th key={ind}>
<button onClick={() => this.sortByDecreasingDate()}>
{elem}
</button>
</th>
);
}
return <th key={ind}>{elem}</th>;
})}
<th>stars</th>
</tr>
</thead>
如果你希望遞增/遞減只作業一次,你可以rated在每個專案上設定一個。你讓它false默認等于,然后當你點擊遞增/遞減時,你將它設定為true。只有當它是false.
我從您的組件中創建了這個Codesandbox作為一個作業示例。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/535650.html
