美文网首页
React-native 组件间的传值

React-native 组件间的传值

作者: Th丶小伟 | 来源:发表于2019-05-05 18:58 被阅读0次

父类传给子类

子组件接收 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',
  }, 
}); 

相关文章

网友评论

      本文标题:React-native 组件间的传值

      本文链接:https://www.haomeiwen.com/subject/phtkoqtx.html