父类传给子类
子组件接收 this.props.name
父组件传值 <HelloWorld name={'爸爸给你取个名字' } />
子类传给父类
子组件传值 :
this.state = { name:'爸爸好!'}
onclick =()=>{
console.log('hello Onclick');
}
父组件利用ref接收:
<HelloWorld ref='HelloWorld'/>
this.refs.HelloWorld.state.name
接收不可以在render()函数里面 可以在componentDidMount() 刷新state状态
componentDidMount(){
this.setState( {name:this.refs.HelloWorld.state.name});
this.refs.HelloWorld.onclick(); //调用子组件方法
}
例子
<!--子类:-->
import React, {Component} from 'react';
import {Platform,
StyleSheet,
Text,
View,
} from 'react-native';
export default class App extends Component{
constructor(props) {
super(props);
this.state = { name:'爸爸好!'}
}
render(){
return(
<View >
<Text style={{paddingTop:20}}>{this.props.name}</Text>
</View>
);
}
onclick =()=>{
console.log('hello Onclick');
}
}
<!--父类:-->
import React, {Component} from 'react';
import {
Platform,
StyleSheet,
Text,
View,
TouchableOpacity
} from 'react-native';
import HelloWorld from './Hello'
export default class App extends Component {
constructor(props) {
super(props);
this.state = {name:'儿子'}
}
render() {
return (
<View style={styles.container}>
<HelloWorld name={'爸爸给你取个名字' } ref='HelloWorld'/>
<Text style={{paddingTop: 20}}> {'e'}</Text>
<TouchableOpacity onPress={this.onParentClick2}>
<Text style={styles.btn}>
{this.state.name}
</Text>
</TouchableOpacity>
{/*<View onPress={ this.onParentClick2()} />*/}
</View>
);
}
componentDidMount(){
this.setState( {name:this.refs.HelloWorld.state.name});
}
onParentClick2 = ()=>{
console.log(this.refs.HelloWorld.state.name);
this.refs.HelloWorld.onclick();//调用子类方法
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
});
网友评论