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

任务需求

一个父组件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(
           this.openModal(rowData)}>
            
          
        )
    }
//...省略代码
}

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

class Parent extends Component {
    this.state = {
        data: '',
    }
    openScoreModal(rowData) {
        //在这里就能拿到Child2想要传递的数据rowData了,现在将这个数据存到父组件的state里面
        this.setState({
              data: rowData
         })
      }
     this.openScoreModal(rowData)}
    />
      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(
             {}}
              animationType = {'none'}>
              
                        
                            
                        
                        
                            {name}
                            Ta点亮了{count}颗星
                        
                    
              
            
        )
    }

你可能感兴趣的:(React Native踩坑之兄弟组件之间通信)