建立子組件
import Taro, { Component, Config } from '@tarojs/taro':引入Component
ShopList :子組件名稱
export default ShopList:導出ShopList組件
ShopList.defaultProps:默認值集合
render :必須實現的方法(須要return 組件的html)javascript
import Taro, { Component, Config } from '@tarojs/taro' import { View, Text, Button } from '@tarojs/components' class ShopList extends Component{ render () {} } ShopList.defaultProps={} export default ShopList
子組件css
{this.props.name}:獲取父組件傳過來的name值
onClick={this.clickBtn} :綁定方法clickBtn
this.props.onChaneg('A2') :調用父組件傳過來的方法 給父組件傳值A2html
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
父組件java
import ShopList from './ShopList' : 引入子組件
<ShopList name='B1' /> :使用子組件並給子組件ShopList 傳遞name值張三1
change :傳遞給子組件用來 子組件向父組件傳值
onChaneg:傳遞給子組件 值是 父組件的 change 方法 主要 值須要 bind(this)這裏的this 是父組件typescript
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> ) } }