一、 首页须要新建一个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组件,组件的好处是只须要负责内容渲染,不作任何事件处理。