美文网首页React交流
React Native踩坑之兄弟组件之间通信

React Native踩坑之兄弟组件之间通信

作者: 大柚子08 | 来源:发表于2017-06-17 17:38 被阅读454次

任务需求

一个父组件Parent下两个子组件Child1和Child2,Child1里是一个列表数据,点击某个元素弹出一个弹框Child2,Child2里展示这个元素的具体信息,大概像下面这样:

2017-06-17_160558.jpg

点击下面的一排头像出现一个弹框,展示该元素的一些信息,我只截取了关键代码。

代码实现

Child2(列表):

class Child2 extends Component {
    openModal(rowData) {
      this.props.openModal(rowData)
    }

    _renderRow(rowData, sectionID, rowID) {
      let avatar = rowData.avatar_url ? rowData.avatar_url : common.avatar;
        return(
          <TouchableOpacity   onPress = {() => this.openModal(rowData)}>
            <Image source = {{uri:avatar}} />
          </TouchableOpacity>
        )
    }
//...省略代码
}

我需要将rowData传递给弹框,使用this.props.openModal(rowData),也就是先把这个值传递到父组件。
Parent(父组件):

class Parent extends Component {
    this.state = {
        data: '',
    }
    openScoreModal(rowData) {
        //在这里就能拿到Child2想要传递的数据rowData了,现在将这个数据存到父组件的state里面
        this.setState({
              data: rowData
         })
      }
    <LikeList 
          openModal = {(rowData) => this.openScoreModal(rowData)}
    />
     <ScoreModal
          data = {this.state.data}
          closeModal = {() => this.closeScoreModal()} 
          modalVisible = {this.state.scoreModalVisible}/>\
//这里就将从Child2拿到的data传给Child1了
}

现在,再由父组件将从Child2拿到的数据传给Child1,由Child1展示。
Child1(弹框):

render() {
        let avatar =  {uri: this.props.data.avatar_url} //拿到的数据
        let name = this.props.data.name //拿到的数据
        let count = this.props.data.count//拿到的数据
        return(
            <Modal visible = {this.props.modalVisible}
              transparent = {true}
              onRequestClose = {() => {}}
              animationType = {'none'}>
              <View style={styles.modalContainer}>
                        <TouchableOpacity style = {styles.closeBtn} onPress = {this.props.closeModal}>
                            <Image source = {Images.closeIcon}/>
                        </TouchableOpacity>
                        <View style = {styles.WhiteContent}>
                            <Text style = {styles.username}>{name}</Text>
                            <Text style = {styles.whiteText}>Ta点亮了{count}颗星</Text>
                        </View>
                    <Image source = {avatar} style = {styles.avatar}/>
              </View>
            </Modal>
        )
    }

相关文章

网友评论

  • 无星灬:nice,没有废话,直接上代码,就喜欢这种简洁明了的风格
    大柚子08:@无星灬 :joy: 谢谢,我表示自己都忘记写的啥了

本文标题:React Native踩坑之兄弟组件之间通信

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