gpt4 book ai didi

javascript - 如何将数据从react子组件传输到父组件

转载 作者:行者123 更新时间:2023-12-02 22:50:19 24 4
gpt4 key购买 nike

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

目前我有:

 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>
)
}
}

最佳答案

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

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

关于javascript - 如何将数据从react子组件传输到父组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58207597/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com