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值張三1
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>
    )
  }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM