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(
          <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>
        )
    }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容