父组件给子组件传递属性跟react一样使用props
案例
import React,{Component} from 'react';
import {View,Text,Image,StyleSheet} from 'react-native';
// 定义子组件
class SiteNameComponent extends React.Component{
constructor(props){
// 子元素的name为什么是有props传递过来的
super(props)
this.state={name:props.name}
}
//触摸事件
updateState=()=>{
const name=this.state.name=='王小二'?'小二去放羊':'小二去吃饭'
this.setState({name:name})
}
render(){
const {name}=this.state
return(
<View>
<Text onPress={this.updateState}>{name}</Text>
</View>
)
}
}
// 父组件
export default class App extends React.Component{
render(){
return(
<View style={styles.container}>
<SiteNameComponent name={'王小二'}/>
</View>
)
}
}
const styles=StyleSheet.create({
container:{
margin:10
}
})