我正在做我的第一个React项目,并且在功能上遇到了麻烦。我的应用程序是预算跟踪器,有两个收入和支出输出表。
每个收入项目(或费用项目)都有一个“ X”,可以根据需要从列表中删除该项目。
我无法编写代码逻辑以通过键或ID删除并重新呈现项目。
现在,我能够创建一个deleteIncomeItem函数,该函数从Parent(App.js)传递给孙子(IncomeItem.js),在这里可以通过“ onClick”调用它。
为使此评论简单,我将仅提供“收入”表的代码,然后将逻辑重复到“支出”表:
//Parent - App.js
import React, { Component } from 'react';
import IncomeList from './components/IncomeList';
import ExpenseList from './components/ExpenseList';
import AddItem from './components/AddItem';
import './App.css';
class App extends Component {
constructor(){
super()
this.state = {
incomeItems: [],
expenseItems: [],
totalIncome: 0,
totalExpense: 0,
color: 'black'
}
this.addBudgetItem = this.addBudgetItem.bind(this);
this.addExpenseItem = this.addExpenseItem.bind(this);
this.deleteIncomeItem = this.deleteIncomeItem.bind(this);
}
addBudgetItem (item, amount) {
let newIncomeTotal = this.state.totalIncome + parseInt(amount);
this.setState({
incomeItems: [...this.state.incomeItems, {item: item, amount: amount}],
totalIncome: newIncomeTotal
})
}
addExpenseItem (expItem, expAmount) {
let newExpenseTotal = this.state.totalExpense + parseInt(expAmount);
this.setState({
expenseItems: [...this.state.expenseItems, {expItem: expItem, expAmount: expAmount}],
totalExpense: newExpenseTotal
})
}
deleteIncomeItem (id) {
//this.setState(prevState => ({
// incomeItems: prevState.incomeItems.filter(el => el != id )
// }));
alert("this works");
}
render() {
return (
<div className="App">
<header className="App-header">
<h1 className="App-title">Monthly Budget</h1>
</header>
<div className="container">
<AddItem addBudgetItem={this.addBudgetItem} addExpenseItem={this.addExpenseItem}/>
<div className="line"></div>
<div className="UIdiv">
<table>
<h1>INCOME ITEMS</h1>
<tr><IncomeList incomeList={this.state.incomeItems} deleteIncomeItem={this.deleteIncomeItem}/></tr>
<p className="income-desc">Total Income: {this.state.totalIncome}</p>
</table>
<table>
<h1>EXPENSE ITEMS</h1>
<tr><ExpenseList expenseList={this.state.expenseItems} /></tr>
<p className="expense-desc">Total Expense: {this.state.totalExpense} </p>
</table>
<h2 style={{color:this.state.color}}> TOTAL BALANCE: {this.state.totalIncome - this.state.totalExpense}</h2>
</div>
</div>
</div>
);
}
}
export default App;
//孩子-IncomeList.js
import React from 'react';
import IncomeItem from './IncomeItem';
import '../App.css';
function IncomeList (props) {
return (
<div className="income-list">
{props.incomeList.map((income, index) => {
return (
<IncomeItem key={index} deleteINCitem={props.deleteIncomeItem} description={income.item} amount={income.amount}/>
)
})}
</div>
)
}
export default IncomeList;
//孙子-IncomeItem.js
import React from 'react';
import '../App.css';
function IncomeItem (props) {
return (
<tr className="incomeItem">
<td className="income-desc">{props.description}</td>
<td className="income-amount">{props.amount}</td>
<td><button className="xBtn" onClick={props.deleteINCitem}>X</button></td>
</tr>
)
}
export default IncomeItem