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

问题描述 投票:0回答:2

我需要弄清楚如何将子组件中接收的数据传输到父组件中的数据。我需要设置我在孩子中收到的控制台日志,以转移到父组件状态。任何帮助,感谢先进的。目前我有:

 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>
        )
      }
    }
javascript reactjs components state
2个回答
0
投票

您已将功能道具传递给子组件。然后在“儿童”组件中只需调用它即可:

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

0
投票

我需要弄清楚如何转移孩子收到的数据组件到父组件中的组件。

1]在父组件中定义一个函数。

myFunc = (myVar) => {
  console.log("myVar: " + myVar)
}

[2)将此函数作为道具传递给子组件:

<ChildComp myFunc={this.myFunc} />

3)然后,随时在子组件中调用此函数:

this.props.myFunc("Print this string")
© www.soinside.com 2019 - 2024. All rights reserved.