1. props参数
//app组件import React, { Component } from 'react'import Person from './components/Person'export default class App extends Component<any, any> { render() { return ( <div> <h2>我是React demo</h2> <hr /> <Person name={'IRIC'} age={20} address="陕西省西安市" hobby={{ my_hobby: ['画画', '跑步', '游泳'] }} /> </div> ) }}//Person组件import { Component } from 'react'interface myHobby { my_hobby: Array<string> // hobby2: string[] //下面的写法与上面相同}interface Iprops { name: string age: number address?: string hobby?: myHobby}export default class Person extends Component<Iprops, any> { render() { return ( <div> <h2>我是Person组件</h2> <p>姓名:{this.props.name}</p> <p>年龄:{this.props.age}</p> <p>address:{this.props.address}</p> <p>hobby:{this.props.hobby?.my_hobby}</p> <ul> {this.props.hobby?.my_hobby.map((item) => { return <li key={item}>{item}</li> })} </ul> </div> ) }}
2. state参数
import { Component } from 'react'interface IState { msg?: string num: number status?: Boolean}export default class Demo extends Component<any, IState> { constructor(props: any, context: any) { super(props, context) this.state = { num: 0 } } add = () => { this.setState((state) => ({ num: state.num + 1 })) } render() { return ( <div> <h2>我是demo组件</h2> <p>num:{this.state.num}</p> <button onClick={this.add}>+</button> </div> ) }}
import { Component } from 'react'interface IState { msg: string num: number status?: Boolean}export default class Demo extends Component<any, IState> { state = { num: 0, msg: 'haha', } add = () => { this.setState((state) => ({ num: state.num + 1 })) } render() { return ( <div> <h2>我是demo组件</h2> <p>num:{this.state.num}</p> <button onClick={this.add}>+</button> <hr /> <h3>{this.state.msg}</h3> </div> ) }}