一、 首頁須要新建一個A文件命名爲A.js
而且在文件裏面寫入如下內容
import React, { Component } from 'react';
import {Text,View,StyleSheet} from 'react-native';
import {B,C} from './Components';
export default class A extends Component {
constructor(props) {
super(props);
this.state = {
title: '我是首頁',
data: [1,2,3,4,5,6],
count: 0
}
}
changeCount = (c) => {
this.setState({
count: c
})
}
render() {
return (
<View style={styles.container}>
<Text style={styles.title}>{this.state.title}</Text>
<B data={this.state.data}/>
<C count={this.state.count} changeCount={this.changeCount}/>
/* this.changeCount在這裏是不須要加括號的,
changeCount={this.changeCount()}這個是錯誤寫法,
若是好奇爲何錯,能夠嘗試加括號執行一遍看看效果
*/
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex:1,
backgroundColor:'#fff',
alignItems: 'center',
justifyContent:'center'
},
title: {
fontSize:25
}
});複製代碼
二、 其次建立另一個文件夾命名爲Components.js
在裏面寫入以下內容
import React, { Component } from 'react';
import {Text,View} from 'react-native';
export const B = ({data}) => {
return (
<View> { data.map((item,index) => { return ( <View style={{width:50,justifyContent:'center',alignItems: 'center'}}> <Text>{item}</Text> </View> ) }) } </View>
)
}
export const C = ({count,changeCount}) => {
return (
<View> <Text>我是C組建</Text> <Text onPress={() => changeCount(count+1)}>改變數值</Text> <Text>{count}</Text> </View>
)
}複製代碼
三、最後的效果
能夠看到列表被渲染出來了,點擊改變數值count也發送了改變,說明傳來的值被執行。
其餘地方一樣能夠引用B/C組件,組件的好處是隻須要負責內容渲染,不作任何事件處理。