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.

52 lines
1.0 KiB

2 years ago
  1. import React from 'react'
  2. class Counter extends React.Component {
  3. // 定义组件状态
  4. state = {
  5. count: 0,
  6. list: ['one', 'two', 'three'],
  7. person: {
  8. name: 'Ken',
  9. age: 20,
  10. },
  11. }
  12. clickHandler = () => {
  13. this.setState({
  14. count: this.state.count + 1,
  15. // // 数组修改,添加数组元素
  16. // list: [...this.state.list, 'four', 'five'],
  17. // // 对象修改
  18. // person: { ...this.state.person, name: 'King' }
  19. // 删除 - filter
  20. list: this.state.list.filter((item) => item !== 'two'),
  21. person: { ...this.state.person, age: '' },
  22. })
  23. }
  24. render() {
  25. return (
  26. <>
  27. <ul>
  28. {this.state.list.map((item) => (
  29. <li key={item}>{item}</li>
  30. ))}
  31. </ul>
  32. <div>
  33. {this.state.person.name} {this.state.person.age}
  34. </div>
  35. <div>
  36. <button onClick={this.clickHandler}>{this.state.count}</button>
  37. </div>
  38. </>
  39. )
  40. }
  41. }
  42. function App() {
  43. return <Counter></Counter>
  44. }
  45. export default App