【问题标题】:How to transfer data from react child component to parent component如何将数据从反应子组件传输到父组件
【发布时间】:2020-02-01 02:12:33
【问题描述】:

我需要弄清楚如何将我在子组件中接收到的数据传输到父组件中的数据。我需要设置我在子组件中收到的控制台日志以转移到父组件状态。

目前我有:

 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


    【解决方案1】:

    您将函数 prop 传递给子组件。然后在子组件中调用它:

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

    【讨论】:

    • 请投票并检查我的答案是否正确,这将有助于其他人
    猜你喜欢
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 2020-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多