简体   繁体   English

如何将数据从反应子组件传输到父组件

[英]How to transfer data from react child component to parent component

I need to figure out how to transfer the data i receive in a child component to the one in parent component.我需要弄清楚如何将我在子组件中收到的数据传输到父组件中的数据。 I need to set the console log i receive in the child to transfer to the parent component state.我需要设置我在子组件中收到的控制台日志以传输到父组件 state。

Currently I have:目前我有:

 Child Comp: 

    import Picker from 'react-giphy-component'
    import React, { Component, PropTypes } from 'react'




    class AddGif extends Component {


      log (gif) {
        console.log(gif.original.mp4)
      }

     returnedGifObject = gif ;


      render () {
        return (
          <div>
            {/* <button></button> */}
            <Picker onSelected={this.log.bind(this)} />
          </div>
        )
      }
    }

    export default AddGif;


    parent element 
class PostBox extends Component {

  constructor(props){
    super(props)
    this.state = {
      title: null,
      postBody: null,
      giphyUrl: null,

      displayGifPicker: false
    }
  }
    getGifState = (selectedUrl) => {
      this.setState({ giphyUrl: selectedUrl})
    }

      render () {
        const {title, postBody} = this.state
        const displayGifPicker = this.state.displayGifPicker
        return (
          <Grid item xl={8}>
         {/* <Card className={classes.card} style={mt4}>  */}
         <Card style={mt4}> 
          <CardContent > 
              <PostInput onChange={this.handleInputChange} onSubmit={this.handleSubmit}/>
              {displayGifPicker ? (<AddGif selectedGif = {this.getGifState} />) : (<Button size="small" onClick={this.displayGifPicker} ><button>Add Gif</button></Button>)}
            <CardActions>
            {/* <Button size="small">Submit VH5</Button> */}
            </CardActions>
          </CardContent>
        </Card>
      </Grid>
        )
      }
    }

You passed the function prop to children component.您将 function 道具传递给子组件。 Then In Children component just call it:然后在子组件中调用它:

log = (gif) => {
   const { selectedGif } = this.props
   console.log(gif.original.mp4)
   selectedGif(gif.original.mp4)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM