1. props参数

  1. //app组件
  2. import React, { Component } from 'react'
  3. import Person from './components/Person'
  4. export default class App extends Component<any, any> {
  5. render() {
  6. return (
  7. <div>
  8. <h2>我是React demo</h2>
  9. <hr />
  10. <Person
  11. name={'IRIC'}
  12. age={20}
  13. address="陕西省西安市"
  14. hobby={{ my_hobby: ['画画', '跑步', '游泳'] }}
  15. />
  16. </div>
  17. )
  18. }
  19. }
  20. //Person组件
  21. import { Component } from 'react'
  22. interface myHobby {
  23. my_hobby: Array<string>
  24. // hobby2: string[] //下面的写法与上面相同
  25. }
  26. interface Iprops {
  27. name: string
  28. age: number
  29. address?: string
  30. hobby?: myHobby
  31. }
  32. export default class Person extends Component<Iprops, any> {
  33. render() {
  34. return (
  35. <div>
  36. <h2>我是Person组件</h2>
  37. <p>姓名:{this.props.name}</p>
  38. <p>年龄:{this.props.age}</p>
  39. <p>address:{this.props.address}</p>
  40. <p>hobby:{this.props.hobby?.my_hobby}</p>
  41. <ul>
  42. {this.props.hobby?.my_hobby.map((item) => {
  43. return <li key={item}>{item}</li>
  44. })}
  45. </ul>
  46. </div>
  47. )
  48. }
  49. }

image.png

2. state参数

  1. import { Component } from 'react'
  2. interface IState {
  3. msg?: string
  4. num: number
  5. status?: Boolean
  6. }
  7. export default class Demo extends Component<any, IState> {
  8. constructor(props: any, context: any) {
  9. super(props, context)
  10. this.state = { num: 0 }
  11. }
  12. add = () => {
  13. this.setState((state) => ({ num: state.num + 1 }))
  14. }
  15. render() {
  16. return (
  17. <div>
  18. <h2>我是demo组件</h2>
  19. <p>num:{this.state.num}</p>
  20. <button onClick={this.add}>+</button>
  21. </div>
  22. )
  23. }
  24. }
  1. import { Component } from 'react'
  2. interface IState {
  3. msg: string
  4. num: number
  5. status?: Boolean
  6. }
  7. export default class Demo extends Component<any, IState> {
  8. state = {
  9. num: 0,
  10. msg: 'haha',
  11. }
  12. add = () => {
  13. this.setState((state) => ({ num: state.num + 1 }))
  14. }
  15. render() {
  16. return (
  17. <div>
  18. <h2>我是demo组件</h2>
  19. <p>num:{this.state.num}</p>
  20. <button onClick={this.add}>+</button>
  21. <hr />
  22. <h3>{this.state.msg}</h3>
  23. </div>
  24. )
  25. }
  26. }