taro组件笔记

创建子组件
import Taro, { Component, Config } from '@tarojs/taro':引入Component
ShopList :子组件名称
export default ShopList:导出ShopList组件
ShopList.defaultProps:默认值集合
render :必须实现的方法(需要return 组件的html)

import Taro, { Component, Config } from '@tarojs/taro'
import { View, Text, Button } from '@tarojs/components'
class ShopList extends Component{
        render () {}
}
ShopList.defaultProps={}
export default ShopList

  

子组件

{this.props.name}:获取父组件传过来的name值
onClick={this.clickBtn} :绑定方法clickBtn
this.props.onChaneg('A2') :调用父组件传过来的方法 给父组件传值A2

import Taro, { Component, Config } from '@tarojs/taro'
import { View, Text, Button } from '@tarojs/components'

class ShopList extends Component{
    
    clickBtn () {
        this.props.onChaneg('A2')
    }

    render () {
        return  (<Vive>
        <Button onClick={this.clickBtn}>调用父组件方法更改父组件值</Button>
        {this.props.name}
        </Vive>)
    }
}

ShopList.defaultProps={
    name:'B',
    onChaneg:null
}
export default ShopList

 

父组件

import ShopList from './ShopList' : 引入子组件
<ShopList name='B1' /> :使用子组件并给子组件ShopList 传递name值B1
change :传递给子组件用来 子组件向父组件传值
onChaneg:传递给子组件 值是 父组件的 change 方法 主要 值需要 bind(this)这里的this 是父组件

import Taro, { Component, Config } from '@tarojs/taro'
import { View, Text, Button } from '@tarojs/components'
import './index.scss'
import ShopList from './ShopList'

export default class Index extends Component {

  /**
   * 指定config的类型声明为: Taro.Config
   *
   * 由于 typescript 对于 object 类型推导只能推出 Key 的基本类型
   * 对于像 navigationBarTextStyle: 'black' 这样的推导出的类型是 string
   * 提示和声明 navigationBarTextStyle: 'black' | 'white' 类型冲突, 需要显示声明类型
   */
  config: Config = {
    navigationBarTitleText: '首页'
  }

  componentWillMount () { }

  componentDidMount () { 
    this.setState({name:'A'})
  }

  componentWillUnmount () { }

  componentDidShow () { }

  componentDidHide () { }

  click () {
    this.setState({name:'A1'}, ()=>{
      console.log(this.state.name)
    })
    console.log(this.state.name)
  }

  change (e) {
    this.setState({name:e}, ()=>{
      console.log(this.state.name)
    })
  }

  render () {
    return (
      <View className='index'>
        <ShopList name='B1' onChaneg={this.change.bind(this)} />
        <Button onClick={this.click}>更改</Button>
        <Text>{this.state.name}</Text>
      </View>
    )
  }
}

 

posted @ 2019-06-15 22:29  苦行_僧  阅读(2737)  评论(0编辑  收藏  举报