美文网首页
React-native 系列6 页面之间相互传值和组件之间相互

React-native 系列6 页面之间相互传值和组件之间相互

作者: 随便你好啦 | 来源:发表于2019-05-27 09:40 被阅读0次

    其实在上一篇也用到了组件之间的传值,不过是父组件向子组件传值,今天我在写首页的时候,需要用到子组件向父组件传值,也就是逆向传值,顺便就在这里总结一下react-native 用react navigation的各种传值方式。

    1.跳转页面并传值

    利用navigate进行跳转,前面的‘xxx’是你要跳转的页面,也在你的导航组件的路由里面的页面名称,后面就是你要传递的参数

    //进入详情页,传递参数
    <Button onPress = {this._pushDetail}
         title = {this.state.backName}/>
    
      _pushDetail(){
        this.props.navigation.navigate('Detail',{
          itemId:'123',
          otherParas: 'add other params you want',
          }
        })
      }
    

    在详情页接收参数:

    static navigationOptions = ({navigation,navigationOptions}) => {
          return {
            title : navigation.getParam('otherParas','suibian'),//后面的这个参数是在前面的参数为null 时填充
          }
    
    2.页面返回,回调参数

    我们有时候会出现下级页面向上级页面回调传值的需求,这时候就需要用到react navigation 的回调传值,
    在首页,也就是一级页面

    //进入详情页,传递参数
      _pushDetail(itemId){
        this.props.navigation.navigate('Detail',{
          itemId:itemId,
          otherParas: 'add other params you want',
          callback:(data) => {
            this.setState({
              backName:data
           })
          }
        })
      }
    

    加上callback回调函数就可以了,然后直接贴详情页的代码:

    _navGoback (){
             const {navigate,goBack,state} = this.props.navigation;
             let backParams = this.state.param
             state.params.callback(backParams);
             this.props.navigation.goBack();    
        }
    

    其实就是将回调函数作为一个参数,让详情页在this.props属性中获取,下面要讲到的子组件向父组件传值其实也是这个道理。

    3.父组件给子组件传值

    这个就比较简单直接贴代码了,一看也就能理解了
    传值:

    import ViewPager from './component/viewpage'
    const imageUrls = ['https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=760528960,2729756840&fm=26&gp=0.jpg', 
         'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1558514797592&di=b7404ddc598d9e395f33f36ef883ebf4&imgtype=0&src=http%3A%2F%2Fc4.haibao.cn%2Fimg%2F600_0_100_0%2F1530690356.3493%2F81eaeb56a5255d33fdb280712f3b252d.jpg',
          'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1558514797592&di=4fc04bc668b9a3ec1e1e75208aeb4b43&imgtype=0&src=http%3A%2F%2Fgss0.baidu.com%2F7Po3dSag_xI4khGko9WTAnF6hhy%2Fzhidao%2Fpic%2Fitem%2F4b90f603738da977a600eedebb51f8198618e31c.jpg'];
     <ViewPager imageUrls ={imageUrls}/>
    

    接收:

    const imageUrls = this.props.imageUrls;
    
    4通过ref 拿到组件,然后传值

    有一些情况下我们不是在创建子组件的时候就向其传值,而是等待某个触发事件,再进行传递,这就需要先获取到这个子组件再向其传值。
    随便写个子组件,直接贴代码:

    class HeaderImage extends React.Component{
        constructor(props){
            super(props);
            this.state = {
                imageUrl: null
            }
        }
    
        _refreshImage(imagesource){
            this.setState({
                imageUrl: imagesource
            })
        }
    
        render(){
           return(
               <View style = {{width:screenW,height : 120}}>
               <Image style = {{flex: 1,backgroundColor: 'red' }}
               source = {{uri: this.state.imageUrl}}
               />
               </View>
           )
        }
    
    }
    

    找到这个组件并传值:

    import ImageComponent from './component/HeaderImage'
    const imageurl = 'https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=760528960,2729756840&fm=26&gp=0.jpg'
    <ImageComponent ref= 'imageShow' style = {{height: 100}}/>
    <Button 
          title = 'show image'
          onPress = {this._showImageNow}/>
     _showImageNow(){
          this.refs.imageShow._refreshImage(imageurl)
        }
    

    完成

    5.子组件向父组件传值

    1.在父组件上定义一个方法接受子组件的传值

    //进入详情页,传递参数
      _pushDetail(itemId){
        this.props.navigation.navigate('Detail',{
          itemId:itemId,
    
    1. 将这个方法传递给子组件,并绑定this
    <HomeItemComponent _pushDetail = {this._pushDetail.bind(this)}/>
    

    3.子组件能通过this.props拿到这个方法,并调用

     _renderItem(path,title){
            // console.warn(path)
            // console.warn(title)
            return(
                <TouchableOpacity onPress = {this._clickItemBlock.bind(this,title)}>
                <View style = {{flexDirection:'column',margin:10,justifyContent:'center',alignItems:'center'}}>
                <Image
                source = {path}
                style = {{width: 45,height:45}}
                />
                <Text style = {{fontSize: 15,color:'#333',textAlign:'center'}}>{title}</Text>
                </View>
                </TouchableOpacity>
            )
        }
    _clickItemBlock(params,event){
            Alert.alert(params)
            // Alert.alert(event)
           this.props._pushDetail(params);
        }
    
    

    这里要说明一点:

    <TouchableOpacity onPress = {this._clickItemBlock.bind(this,title)}>
    _clickItemBlock(params,event){}
    

    这里的title是作为bind()函数的参数传过来的。bing(this)的参数传递方式,就是通过后面的参数进行传递的。

    6.通知传值

    如果在组件通信的过程中,是拿不到该组件的,就可以使用通知传值,下面贴一下通知的代码:
    监听通知:

    componentDidMount(){
            //添加监听者
            this.listener = DeviceEventEmitter.addListener('changeTitle',(changeTitle)=>{
                this.setState({
                    originTitle: changeTitle
                })
            })
        }
       
        componentWillUnmount(){
          //销毁监听者
          this.listener.remove()
        }
    

    发送通知:

    <Text style = {{fontSize : 24}}
              onPress = { ()=> {
                  DeviceEventEmitter.emit('changeTitle','是时候该改变了')
              }}>change title</Text>
    

    以上就是我在react native中通信采用的方式,希望对您有所帮助。
    demo地址

    相关文章

      网友评论

          本文标题:React-native 系列6 页面之间相互传值和组件之间相互

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