You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

56 lines
1.1 KiB

2 years ago
  1. import React from 'react'
  2. function ListItem({ item, delItem }) {
  3. return (
  4. <>
  5. <h3>{item.name}</h3>
  6. <p>{item.price}</p>
  7. <p>{item.info}</p>
  8. <button onClick={() => delItem(item.id)}>删除</button>
  9. </>
  10. )
  11. }
  12. class App extends React.Component {
  13. state = {
  14. list: [
  15. {
  16. id: 1,
  17. name: '超级好吃的棒棒糖',
  18. price: 18.8,
  19. info: '开业大酬宾,全场8折',
  20. },
  21. {
  22. id: 2,
  23. name: '超级好吃的大鸡腿',
  24. price: 34.2,
  25. info: '开业大酬宾,全场8折',
  26. },
  27. {
  28. id: 3,
  29. name: '超级无敌的冰激凌',
  30. price: 14.2,
  31. info: '开业大酬宾,全场8折',
  32. },
  33. ],
  34. }
  35. // 给子组件传递的函数
  36. delItem = (id) => {
  37. this.setState({
  38. list: this.state.list.filter((item) => item.id !== id),
  39. })
  40. }
  41. render() {
  42. return (
  43. <div>
  44. {this.state.list.map((item) => (
  45. <ListItem key={item.id} item={item} delItem={this.delItem} />
  46. ))}
  47. </div>
  48. )
  49. }
  50. }
  51. export default App