当前位置: 首页 > 工具软件 > taro-script > 使用案例 >

Taro+TypeScript - state 和 props声明使用

许学真
2023-12-01
import { ComponentType } from 'react'
import Taro, { Component, Config } from '@tarojs/taro'
import { View, Button, Text } from '@tarojs/components'
import { observer, inject } from '@tarojs/mobx'

import './index.scss'
// 声明props类型
type PropsType = {
  counter: {
    counter: number,
    increment: Function,
    decrement: Function,
    incrementAsync: Function
  },
  address: string
}
// 声明state类型
type StateType = {
  name: string,
  age: number
}
// 声明接口
interface Index {
  props: PropsType,
  state: StateType
}
// mobx注入
@inject('counter')
@observer
class Index extends Component {
  // state的初始化在constructor中
  constructor (props) {
    super(props)
    // 初始化
    this.state = {
      name: 'Test',
      age: 18
    }
  }

  config: Config = {
    navigationBarTitleText: '首页'
  }

  componentWillMount () { }
  // mobx数据改变进行渲染函数()
  componentWillReact () {
	console.log('数据发生变化')
  }

  componentDidMount () { }

  componentWillUnmount () { }

  componentDidShow () { }

  componentDidHide () { }

  increment = () => {
    const { counter } = this.props
    counter.increment()
  }

  decrement = () => {
    const { counter } = this.props
    counter.decrement()
  }

  incrementAsync = () => {
    const { counter } = this.props
    counter.incrementAsync()
  }
  stateChange () {
    this.setState({
      name: 'wang'
    })
  }

  render () {
    const { counter: { counter } } = this.props
    const { name } = this.state
    return (
      <View className='index'>
        <Button onClick={this.increment}>+</Button>
        <Button onClick={this.decrement}>-</Button>
        <Button onClick={this.incrementAsync}>Add Async</Button>
        <Text>{counter}</Text>
        <Button onClick={this.stateChange}>修改姓名</Button>
        <Text>{name}</Text>
      </View>
    )
  }
}
export default Index  as ComponentType
 类似资料: